1

I read this blog and this question and its answer, but found they are talking about single file only

    // Parse our multipart form, 10 << 20 specifies a maximum
    // upload of 10 MB files.
    r.ParseMultipartForm(10 << 20)
    // FormFile returns the first file for the given key `myFile`
    // it also returns the FileHeader so we can get the Filename,
    // the Header and the size of the file
    file, handler, err := r.FormFile("myFile")
    if err != nil {
        fmt.Println("Error Retrieving the File")
        fmt.Println(err)
        return
    }
    defer file.Close()

How can I upload multiple files at one shoot?

If I have the below JavaScript code that upload multiple files, how can I read handle it in Go server

const formData = new FormData();
const photos = document.querySelector('input[type="file"][multiple]');

formData.append('title', 'My Vegas Vacation');
for (let i = 0; i < photos.files.length; i++) {
  formData.append('photos', photos.files[i]);
}

fetch('https://example.com/posts', {
  method: 'POST',
  body: formData,
})
.then(response => response.json())
.then(result => {
  console.log('Success:', result);
})
.catch(error => {
  console.error('Error:', error);
});

With HTML element:

<input type="file" multiple />

Or with:

const formData = new FormData();
/*more specific selector: 
  "input[type=file][name=file1],input[type=file][name=file2],input[type=file][name=file3]"*/
document.querySelectorAll("input[type=file]").forEach(
    input=>formData.append('photos',input.files[0]);

If HTML elements are separate like:

<input name="file1" type="file" />
<input name="file2" type="file" /> 
<input name="file3" type="file" /> 
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Hasan A Yousef
  • 22,789
  • 24
  • 132
  • 203

1 Answers1

3

Request.FormFile is helper method for accessing a single file in Request.MultipartForm. Use Request.MultipartForm directly to access multiple files for a key:

err := r.ParseMultipartForm(10 << 20)
if err != nil {
     // handle error
}
for _, fh := range r.MultipartForm.File["photos"] {
    f, err := fh.Open()
    if err != nil {
        // Handle error
    }
    // Read data from f
    f.Close()
}

If the input elements have unique keys as in the last snippet of HTML, then call r.FormFile(key) for each unique key.

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242