MultipartFile+ajax图片上传

今天调接口,一直报org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file_data' is not present

,用postman能正常请求。觉得是前端写法有问题,网上查了下发现是js写法有问题,记录一下以后方便找

前端页面

<div id="uploadForm">
    <input id="file" type="file"/>
    <button id="upload" type="button">upload</button>
</div>
js
$("#upload").on("click", function () {debugger;
        var s = $('#file')[0].files[0];
        var formData = new FormData();
        formData.append("file_data", s);
        formData.append("type", "1");
        $.ajax({
            url: "/jinhua-web/web/fileOption/fileUpload",
            type: 'POST',
            cache: false,
            data: formData,
            processData: false,
            contentType: false,
            success: function (result) {
            },
            error: function (err) {
            }
        });
    });

后端controller

@RequestMapping(value = "/fileUpload",method = RequestMethod.POST)
    public JSONObject fileUpload(@RequestParam("file_data") MultipartFile file_data, @RequestParam("type") String type,
                                 HttpServletRequest request){
        JSONObject result = new JSONObject();
        Path tempPath =Paths.get(Commonconstants.FILE_TEMP_PATH);
        tempPath = tempPath.resolve(type);
        Path realPath = Paths.get(rootPath,tempPath.toString());
        if (!Files.exists(realPath)){
            try {
                Files.createDirectories(realPath);
            } catch (IOException e) {
                result.put(Commonconstants.CODE,1);
                result.put(Commonconstants.MESSAGE,e.getLocalizedMessage());
                e.printStackTrace();
                return result;
            }
        }
        String fileName = UUID.randomUUID().toString().replace("-","")+".jpg";
        tempPath = tempPath.resolve(fileName);
        realPath = realPath.resolve(fileName);
        try {
            file_data.transferTo(realPath.toFile());
        } catch (IOException e) {
            result.put(Commonconstants.CODE,1);
            result.put(Commonconstants.MESSAGE,e.getLocalizedMessage());
            e.printStackTrace();
            return result;
        }
        result.put(Commonconstants.CODE,0);
        result.put("url",tempPath.toString());
        return result;
    }



©️2020 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值