-
Notifications
You must be signed in to change notification settings - Fork 24
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
5aef0ea
commit 9f2f40f
Showing
1 changed file
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
package multipart | ||
|
||
import ( | ||
"fmt" | ||
fileutils "github.com/jfrog/gofrog/io" | ||
"io" | ||
"mime/multipart" | ||
"os" | ||
) | ||
|
||
type FileWriterFunc func(fileName string) (io.WriteCloser, error) | ||
|
||
func ReadFromStream(multipartReader *multipart.Reader, fileWriterFunc FileWriterFunc) error { | ||
for { | ||
// Read the next file streamed from client | ||
fileReader, err := multipartReader.NextPart() | ||
if err != nil { | ||
if err == io.EOF { | ||
break | ||
} | ||
return fmt.Errorf("failed to read file: %w", err) | ||
} | ||
fileName := fileReader.FileName() | ||
fileWriter, err := fileWriterFunc(fileName) | ||
if err != nil { | ||
return err | ||
} | ||
defer fileutils.Close(fileWriter, &err) | ||
|
||
// Stream file directly to disk | ||
if _, err = io.Copy(fileWriter, fileReader); err != nil { | ||
return fmt.Errorf("failed writing '%s' file: %w", fileName, err) | ||
} | ||
} | ||
return nil | ||
} | ||
|
||
func exampleFunc(filepath string) (fileWriter io.WriteCloser, err error) { | ||
Check failure on line 38 in http/multipart/multipart.go
|
||
fileWriter, err = os.Create(filepath) | ||
if err != nil { | ||
return nil, fmt.Errorf("create file: %w", err) | ||
} | ||
return | ||
} | ||
|
||
func myMain(filepath string) { | ||
Check failure on line 46 in http/multipart/multipart.go
|
||
ReadFromStream(nil, exampleFunc) | ||
Check failure on line 47 in http/multipart/multipart.go
|
||
} |