Java的Springboot框架结合AJAX实现form表单图片上传-详解

Java的Springboot框架结合AJAX实现form表单图片上传-详解

页面

<form>
	<div class="row" style="margin-top: 3px;">
		<div class="col-md-2" style="margin-top: 5px;" ><span>场地图片:</span></div>
		<div class="col-md-9 " style="padding-left:0px">
			<input type="file" id="file" name="file" class="form-control" required>
			<input type="text" hidden id="type_image" name="type_image" value=''>
		</div>
	</div>
	<div class="row"style="margin-top: 3px;">
		<div class="col-md-2" style="margin-top: 5px;"><span>联系人:</span></div>
		<div class="col-md-9 " style="padding-left:0px">
			<input type="text" id="type_linkman" class="form-control" readonly="readonly" required autofocus value=''>
		</div>
	</div>
</form>

JavaScript

/*图片AJAX上传*/
$("body").on("change","#file",function(e){
    var formData = new FormData($("#typeForm")[0]);
    $.ajax({
        url: "/admin/upload",
        type: "post",
        data: formData,
        contentType:"application/x-www-form-urlencoded; charset=utf-8",
        async: false,
        cache: false,
        contentType: false,
        processData: false,
        success: function(data){
            console.log(data)
            $("#type_image").attr("value",data);
        }
    });
});

Controller处理

@RestController()
@RequestMapping("/admin")
public class AdminController {

    @Value("${filePath}")
    private String filePath = "C:\upload";
	
	/**
     * 上传图片
    */
    @PostMapping("/upload") // 等价于 @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String uplaod(HttpServletRequest req, @RequestParam("file") MultipartFile file) {//1. 接受上传的文件  @RequestParam("file") MultipartFile file
        try {
            //2.根据时间戳创建新的文件名,这样即便是第二次上传相同名称的文件,也不会把第一次的文件覆盖了
            //获取文件的后缀名 .jpg
            int lastIndexOf = file.getOriginalFilename().lastIndexOf(".");
            String suffix = file.getOriginalFilename().substring(lastIndexOf);
            String fileName = System.currentTimeMillis() + suffix;
            //3.通过req.getServletContext().getRealPath("") 获取当前项目的真实路径,然后拼接前面的文件
            //String destFileName = req.getServletContext().getRealPath("") + "uploaded" + File.separator + fileName;
            String destFileName = filePath+File.separator+fileName;
            //4.第一次运行的时候,这个文件所在的目录往往是不存在的,这里需要创建一下目录(创建到了webapp下uploaded文件夹下)
            File destFile = new File(destFileName);
            destFile.getParentFile().mkdirs();
            //5.把浏览器上传的文件复制到希望的位置
            file.transferTo(destFile);
            //6.把文件名放在model里,以便后续显示用
            return "/"+fileName;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return "上传失败," + e.getMessage();
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败," + e.getMessage();
        }
    }
}

OK!分享一波用法!不会的给我私信或者回复留言!
觉得有帮助的可以关注一波!经常分享编程踩坑经验!

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值