vue axios实现文件上传后台springboot

引入jar

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>

html代码

<div id="uploadDiv">
    <input type="file" value="" id="file" @change="uploadConfig" name="file">
</div>
<script type="text/javascript">
    new Vue({
        el: '#uploadDiv',
        methods: {
            uploadConfig: function (e) {
                    var formData = new FormData();
                    formData.append('file', e.target.files[0]);
                    var  url = 'fileUpload';
                    var config = 'multipart/form-data;';
                    // axios({
                    //     method:"post",
                    //     url:"fileUpload",
                    //     data:{
                    //         file:'11'
                    //     }
                    // }).then((res)=>{console.log(res.data)})
                    axios.post(url,formData, config).then(function (response) {
                        console.log(response.data)

                    })
            }
        }
    })



    </script>

开始用的注释的方法,但是后台接收总是为null;

java代码

@RequestMapping(value = "/fileUpload",method =RequestMethod.POST )
public String imgUpload(@RequestParam(value = "file",required = false) MultipartFile file) throws IOException {
   long  startTime=System.currentTimeMillis();
    System.out.println("fileName:"+file.getOriginalFilename());
    String path="E:/"+new Date().getTime()+file.getOriginalFilename();

    File newFile=new File(path);
    //通过CommonsMultipartFile的方法直接写文件(注意这个时候)
    file.transferTo(newFile);
    long  endTime=System.currentTimeMillis();
    System.out.println("采用file.Transto的运行时间:"+String.valueOf(endTime-startTime)+"ms");
    return "/success";

}

开始用的接收参数为

CommonsMultipartFile

报错

org.springframework.web.method.annotation.MethodArgumentConversionNotSupportedException: Failed to convert value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'org.springframework.web.multipart.commons.CommonsMultipartFile'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'org.springframework.web.multipart.commons.CommonsMultipartFile': no matching editors or conversion strategy found]

 Failed to convert value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'org.springframework.web.multipart.commons.CommonsMultipartFile'

修改方式

在application.yml中添加multipart: enabled: true

然后替换 @RequestParam CommonsMultiPartFile 为 @RequestParam MultipartFile file

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章