Springboot formdata ajax表单数据和图片一起上传

参考:https://blog.csdn.net/wqh8522/article/details/78971260

https://blog.csdn.net/qq_41669724/article/details/80748952

html文件代码片段

<form id="studentAddForm" method="post" enctype="multipart/form-data" οnsubmit="return false">
	学号:
	<input id="studentNo" name="studentNo" type="text">
	</br>
	姓名:
	<input id="studentName" name="studentName" type="text">
	</br>
	性别:
	<input id="studentSex" name="studentSex" type="text">
	</br>
	头像:
	<input id="file" name="file" type="file">
	</br>
	<input type="button" value="添加" οnclick="checkForm()">
</form>
<script>
    function checkForm() {
        var formData = new FormData($("#studentAddForm")[0]);
        $.ajax({
            url : "/saveStudentInfo",
            type : 'POST',
            data : formData,
            cache: false,
            async: false,
            processData : false,  //必须false才会避开jQuery对 formdata 的默认处理
            contentType : false,  //必须false才会自动加上正确的Content-Type
 
            success: function (data) {
                console.log("成功");
		/*
		layer.alert("增加成功", {icon: 6}, function () {
                    window.parent.location.reload(); //刷新父页面
                    // 获得frame索引
                    var index = parent.layer.getFrameIndex(window.name);
                    //关闭当前frame
                    parent.layer.close(index);
                });
		*/
            },
            error: function (data) {
                console.log("失败");
		/*
		layer.msg(data.message, {time: 2000});
		*/
            }
        });
    }
</script>

其中 

processData设置为false。因为data值是FormData对象,不需要对数据做处理。
<form>标签添加enctype="multipart/form-data"属性。
cache设置为false,上传文件不需要缓存。
contentType设置为false,不设置contentType值,因为是由<form>表单构造的FormData对象,且已经声明了属性enctype="multipart/form-data",所以这里设置为false。
上传后,服务器端代码需要使用从查询参数名为file获取文件输入流对象,因为<input>中声明的是name="file"

processData: 要求为Boolean类型的参数,默认为true。默认情况下,发送的数据将被转换为对象(从技术角度来讲并非字符串)以配合默认内容类型"application/x-www-form-urlencoded"。如果要发送DOM树信息或者其他不希望转换的信息,请设置为false。
Controller

@PutMapping("/article/img/upload")
    public MarkDVo uploadImg(@RequestParam("editormd-image-file") MultipartFile multipartFile)  {
        if (multipartFile.isEmpty() || StringUtils.isBlank(multipartFile.getOriginalFilename())) {
           throw new BusinessException(ResultEnum.IMG_NOT_EMPTY);
        }
        String contentType = multipartFile.getContentType();
        if (!contentType.contains("")) {
            throw new BusinessException(ResultEnum.IMG_FORMAT_ERROR);
        }
        String root_fileName = multipartFile.getOriginalFilename();
        logger.info("上传图片:name={},type={}", root_fileName, contentType);
        //处理图片
        User currentUser = userService.getCurrentUser();
        //获取路径
        String return_path = ImageUtil.getFilePath(currentUser);
        String filePath = location + return_path;
        logger.info("图片保存路径={}", filePath);
        String file_name = null;
        try {
            file_name = ImageUtil.saveImg(multipartFile, filePath);
            MarkDVo markDVo = new MarkDVo();
            markDVo.setSuccess(0);
            if(StringUtils.isNotBlank(file_name)){
                markDVo.setSuccess(1);
                markDVo.setMessage("上传成功");
                markDVo.setUrl(return_path+File.separator+file_name);
                markDVo.setCallback(callback);
            }
            logger.info("返回值:{}",markDVo);
            return markDVo;
        } catch (IOException e) {
            throw new BusinessException(ResultEnum.SAVE_IMG_ERROE);
        }
    }
/**
     * 保存文件,直接以multipartFile形式
     * @param multipartFile
     * @param path 文件保存绝对路径
     * @return 返回文件名
     * @throws IOException
     */
    public static String saveImg(MultipartFile multipartFile,String path) throws IOException {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        FileInputStream fileInputStream = (FileInputStream) multipartFile.getInputStream();
        String fileName = Constants.getUUID() + ".png";
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path + File.separator + fileName));
        byte[] bs = new byte[1024];
        int len;
        while ((len = fileInputStream.read(bs)) != -1) {
            bos.write(bs, 0, len);
        }
        bos.flush();
        bos.close();
        return fileName;
    }

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
前端代码: 1. 定义html表单,使用form标签包裹 ```html <form id="myForm" method="post"> <label for="username">用户名:</label> <input type="text" id="username" name="username"><br><br> <label for="password">密码:</label> <input type="password" id="password" name="password"><br><br> <button type="submit" id="submitBtn">提交</button> </form> ``` 2. 监听表单提交事件,使用jquery发送ajax请求 ```javascript $('#myForm').submit(function(event) { event.preventDefault(); // 阻止表单默认提交行为 var formData = { 'username': $('input[name=username]').val(), 'password': $('input[name=password]').val() }; $.ajax({ type: 'POST', url: '/api/login', data: JSON.stringify(formData), dataType: 'json', contentType: 'application/json', success: function(data) { console.log(data); }, error: function(jqXHR, textStatus, errorThrown) { console.log(jqXHR.responseText); } }); }); ``` 后端代码: 1. 定义接收请求的controller方法 ```java @RestController @RequestMapping("/api") public class LoginController { @PostMapping("/login") public ResponseEntity<?> login(@RequestBody Map<String, String> request) { String username = request.get("username"); String password = request.get("password"); // 处理登录逻辑 return ResponseEntity.ok("登录成功"); } } ``` 2. 使用@RequestBody注解接收json数据,并使用ResponseEntity返回响应数据 ```java @PostMapping("/login") public ResponseEntity<?> login(@RequestBody Map<String, String> request) { String username = request.get("username"); String password = request.get("password"); // 处理登录逻辑 return ResponseEntity.ok("登录成功"); } ``` 步骤讲解: 1. 定义html表单,使用form标签包裹。 2. 监听表单提交事件,阻止表单默认提交行为,获取表单数据,使用jquery发送ajax请求。 3. 后端定义接收请求的controller方法,使用@RequestBody注解接收json数据。 4. 处理接收到的数据,返回响应数据。在本例中,使用ResponseEntity.ok()方法返回登录成功信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值