通过JQuery的ajax+SpringBoot的方式上传图片

环境:
前端使用JQuery.ajax()
后端SpringBoot2.x

1. 前端发送

这里每次发送一个文件,多文件请参考其他博文。

1.1 重点

这里发送文件数据的时候借助了 FormData类,当然也可以不借助,自己进行封装。


在使用ajax方法的时候,需要添加配置:

contentType默认是:application/x-www-form-urlencoded,需要配置为multipart/form-data,简单配置可以配置为false。

processData默认为true,会对传入的数据格式化为字符串,需要配置为false

<body>
	<form id="form">
	    <input type="file" name="image" id="file">
	    <button type="button" onclick="confirmData()">提交</button>
	</form>
</body>
<script>
function addDynamic() {
        let formData = new FormData($('#form')[0]);
        // let file = $('#file')[0].files[0];
        // formData.append("file", file);
        // 可以在formData中添加自己的参数
        formData.append("userId", window.localStorage.getItem("userId"));
        $.ajax({
            url: '/tlgms/dynamic/addDynamic',
            data: formData,
            contentType: false,
            processData: false,
            type: 'post',
            dataType: 'json',
            success: function (res) {
				// 成功参数
            }
        })
    }
</script>

2. 后端接收

使用 MultipartFile 接受文件

@RestController
@RequestMapping("dynamic")
public class DongtaiController extends ApiController {
	@PostMapping("addDynamic")
    public String addDynamic(@RequestParam(required = false) MultipartFile image, Dongtai dongtai) {
        String name = "src/main/webapp/static/images/upload/" + System.currentTimeMillis() + image.getOriginalFilename();
        try (OutputStream outputStream = new FileOutputStream(name)){
            byte[] bytes = image.getBytes();
            outputStream.write(bytes);
            outputStream.flush();
            dongtai.setFmImg("/tlgms/" + name.substring(16));
            dongtaiDao.insert(dongtai);
            return JSONUtil.toJsonStr(new R(0, ""));
        } catch (IOException e) {
            e.printStackTrace();
            return JSONUtil.toJsonStr(new R(1, ""));
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值