Empty MultipartFile[] when sending files from Vue to SpringBoot controller

匆匆过客 提交于 2020-03-05 06:06:43

问题


I'm doing a program that will help me to make monthly reports and I stuck at uploading photos which I need for one kind of the reports. For some reason, it doesn't get an array in the controller. I use Springboot RestController at the backend and Vue with BootstrapVue and vue-resource on the other side.

index.html (BootstrapVue):

  <b-form-file
    v-model="photos"
    accept="image/*"
    multiple
    placeholder="..."
  ></b-form-file>

  <b-button @click="uploadPhotos">Upload</b-button>

inside vuemain.js:

  data: {
    photos: null,
  },
  methods: {
    uploadPhotos(){
    var formData = new FormData();
    formData.append("photos", this.photos);
    this.$http.post('reports/photo', formData).then(result => {
      ...
    })
  }, ...

inside Controller:

@PostMapping("/photo")
public void addPhoto(@RequestParam("photos") MultipartFile[] photo) {
    System.out.println(photo.length); // shows 0
}

what I see inside Params at browser:

XHRPOSThttp://localhost:8080/reports-maker/reports/photo
[HTTP/1.1 500  326ms]
Request payload 
-----------------------------4469196632041005505545240657
Content-Disposition: form-data; name="photos"
[object File],[object File],[object File],[object File]
-----------------------------4469196632041005505545240657--

So for some reason at this point @RequestParam("photos") MultipartFile[] photo it's empty array. But if I change it to just one photo like this: @RequestParam("photos") MultipartFile photo and send one from js: formData.append("photos", this.photos[0]); everything works nicely and photo gets uploaded to the server.

It's my first experience with Vue and to be honest I don't want to go deep into JS learning, so probably there is some silly mistake somewhere. Any way I can use a loop in JS method to upload them one by one, but that would be so ugly. I hope there is a better way to do it (without any additional JS libraries of course).


回答1:


If you use axios then you should add header

var headers = {
    'Content-Type': 'multipart/form-data',
};

axios.post(
    'reports/photo', 
    formData,
    {
        headers: headers,
    }
)
...

to be able send files to the server.




回答2:


I found an acceptable solution here https://stackoverflow.com/a/33921749/11508625 Rossi Robinsion's code works nicely. At least it looks better than sending files in separate requests one by one.

The answer is based on using getFileNames() which helps to iterate on files inside a request even if they are not in the array.



来源:https://stackoverflow.com/questions/60035869/empty-multipartfile-when-sending-files-from-vue-to-springboot-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!