Reputation: 91
I am using Go to write server-side for a music streaming service. I need to be able to handle album uploads. I want admins to be able to go to http://lisn.rocks/upload, select a folder that has to contain meta.json
, cover.jpg
, and some .mp3
song files, click upload and the rest to be handled by server.
Here is a simple HTML page I'm using to test this functionality:
<html>
<head><title>Album Upload</title></head>
<body>
<form enctype="multipart/form-data" action="/upload" method="POST">
<input type="file" name="album" webkitdirectory directory multiple> <br>
<input type="submit" value="Upload">
</form>
</body>
</html>
I need a handler function that would be able to look at the meta.json
file, check its contents and do stuff based on what's there. The meta.json
contains all the info I need. Now, I don't need an extensive explanation about reading JSON with Go or other things that go along with it.
I just need to read all files from that folder as separate files. Instead, Go sees them all as a single album
file field when I do request.FormFile("album")
.
Upvotes: 2
Views: 3072
Reputation: 389
Handling multiple files upload in go can be done by using the MultipartForm field of the request struct.
multipartFormData := req.MultipartForm
for _, v := range multipartFormData.File["attachments"] {
fmt.Println(v.Filename, ":", v.Size)
uploadedFile, _ := v.Open()
// then use the single uploadedFile however you want
// you may use its read method to get the file's bytes into a predefined slice,
//here am just using an anonymous slice for the example
uploadedFile.Read([]byte{})
uploadedFile.Close()
}
Upvotes: 2
Reputation: 51557
As the documentation for FormFile
says, it only returns the first file. When the form is submitted, the album
field will be an array and you have to use a multipart stream to process each individual file.
rd, err:=request.MultipartReader()
for {
part, err:=rd.NextPart()
if err==io.EOF {
break
}
data,err:=ioutil.ReadAll(part)
fileName:=part.FileName()
part.Close()
}
You need to add error handling and data processing, etc.
Upvotes: 1