springboot带参数的文件上传

这个工程是在内网环境进行开发,u口也被封住了,所以不能把代码拷贝出来,于是把业务部分进行脱敏处理,核心代码手写一遍如下:
一、html关键代码

<form id = "createForm" method="post" enctype="multipart/form-data">
<div class="form-group"><div class="col-xs-3">活动名称</div><div class="col-xs-7><input type="text" class="activity" id="activityName" palcegolder="请输入" /></div></div>
<div class="form-group"><div class="col-xs-3">文件上传</div><div class="col-xs-7><input type="file" class="activity" id="files" name="files" multiple="multiple"/></div></div>
</form>
<button id="activity" class="btn" type="button">确定</button>

 

 

二、js代码

$('#activity').click(function(event)){
	var fd = new FormData();//如果使用var data = $('#createForm').serialize();它无法提交文件提交
	for(var i = 0;i<$("#files")[0].files.length;i++){
		fd.append("files",$("#files")[0].files[i]);
	}
	fd.append("activityName",$("#activityName").val());
	//因为要符合项目整体风格,所以这里采用udesk。正常使用ajax就可以
	udesk.ajax({
		url:"",
		method:"post",
		contentType:false,
		processData:false,
		async:false,
		data: fd
	}).done(function(res,textStatus,jqXHR){
		document.getElementById("createForm").reset();
		$("#createForm").modal('hide');
	}
}

 

 

三、Controller代码

@ResponseBody
@RequestMapping(value="/insertActivity",method=RequestMethod.POST)
public void insertActivity(HttpServletRequest request,@RequestParam(value = "activityName",required = false) String activityName){
	CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
	if(commonsMultipartResolver.isMultipart(request)){
		MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
		List<MultipartFile> list = multipartHttpServletRequest.getFiles("files");
		for(MultipartFile multipartFile:list){
			String fileName = multipartFile.getOriginalFilename();//文件真名
			String substring = fileName.substring(fileName.lastIndexOf("."));//后缀
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			String time = dateFormat.format(new Date());
			String upName = UUID.randomUUID().toString()+substring;//修改后的
			String path = uploadLocation+time+"\\"+upName;
			File file = new File(uploadLocation+time);
			if(!file.exists()){
				file.mkdirs();
			}
			try{
				multipartFile.transferTo(new File(file,name));
			} catch (IOException E){
				E.printStackTrace();
			}
		}
}
}
 
 
posted @ 2021-02-20 15:03  牧之丨  阅读(2991)  评论(0编辑  收藏  举报