springboot中使用js.ajax()方法和multipartfile类实现文件异步上传-springboot(2)

前言

今天忽然发现,之前springmvc中我经常使用的文件上传的js包不可用在springboot中不可用了,使用包里的方法访问不到后台上传文件接口,只能自己重新实现了。
之前没有接触过这块,世纪项目中也只用到过几次而已,只好多踩一踩坑

正文

直接先把代码列出来吧
后台controller

	/**
     * 文件上传
     * @param file 接收前端的formdata
     * @return 包含上传信息的json
     */
	@RequestMapping(value = "/fileup", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject singleFileUpload(@RequestParam("file")MultipartFile file){
        JSONObject jsonObject = new JSONObject();
        if (file.isEmpty()) {
            jsonObject.put("result", -1);
            return jsonObject;
        }
        String fileName = file.getOriginalFilename();
        StringBuilder stringBuilder = new StringBuilder();
        File fileDir = new File("src/main/resources/static/");
        String path = fileDir.getAbsolutePath();
        if(!fileDir.exists()){
            fileDir.mkdir();
        }
        try {
            file.transferTo(new File(path, fileName));
            jsonObject.put("result", 1);
            jsonObject.put("message", "ok");
            jsonObject.put("url", stringBuilder.append(path).append(fileName).toString());
        } catch (Exception e) {
            jsonObject.put("result", 0);
            e.printStackTrace();
        }

        return jsonObject;
    }

将文件保存在src/main/resources/static/下,并且使用文件原名。

前端代码:
前端要引入jquery,要用到$.ajax()




    
    Uplaod
    






JSON

返回的url为:

注释掉的是通过form表单提交,会存在页面刷新的感觉。
运行试试
springboot中使用js.ajax()方法和multipartfile类实现文件异步上传-springboot(2)_第1张图片
提交后,前端显示上传成功
springboot中使用js.ajax()方法和multipartfile类实现文件异步上传-springboot(2)_第2张图片

在后台查看
springboot中使用js.ajax()方法和multipartfile类实现文件异步上传-springboot(2)_第3张图片
OK,代码可用。

你可能感兴趣的:(springboot,springboot,文件上传)