版权声明:UU小七 :转载请标注哦!^v^ https://blog.csdn.net/qq_36474549/article/details/84108332
前台页面:
<div class="form-group">
<label>添加商品图片</label>
<input type="file" id="file" name="file" accept="image/*"
class="file-upload-default">
<div class="input-group col-xs-12">
<input type="text" id="filename" name="filename" id="product_pic"
name="product_pic" class="form-control file-upload-info"
disabled placeholder="请导入图片路径">
<span class="input-group-append">
<input id="btn_addPic" class="file-upload-browse btn btn-gradient-primary"
type="button" value="添加"></input>
</span>
</div>
</div>
Ajax提交:
function uploadpic() {
var formData = new FormData();
formData.append('myfile', $('#file')[0].files[0]);//序列化图片值
$.ajax({
async: false,//要求同步 不是不需看你的需求
url : "/generalManager/addProductPic",
type : 'POST',
data : formData,
processData : false, //必须false才会避开jQuery对 formdata 的默认处理
contentType : false, //必须false才会自动加上正确的Content-Type
success : function(data) {
},
error : function(er) {
alert(er);
}
});
}
后台Controller层:
@RequestMapping(value = "/addProductPic", produces = "text/html;charset=utf-8", method = RequestMethod.POST)
@ResponseBody
public void importPicFile(@RequestParam(value = "myfile", required = false) MultipartFile myfile,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
String fileName = "";
if (myfile.isEmpty()) {
} else {
//取得当前上传文件的文件名称
String originalFilename = myfile.getOriginalFilename();
//获得图片后缀名称,如果后缀不为图片格式,则不上传
String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
//获得上传路径的绝对路径地址(/upload)-->
// String realPath = request.getSession().getServletContext().getRealPath("/" + DirectoryName);
//重命名上传后的文件名 111112323.jpg
fileName = getFileName() + suffix;
System.out.println("***************"+fileName);
//定义上传路径 .../upload/111112323.jpg
String filePath = "F:\\UpLoad\\images\\";
//封装上传文件位置的全路径
File uploadPath = new File(filePath, fileName);
//把本地文件上传到封装上传文件位置的全路径
myfile.transferTo(uploadPath);
}
}
public String getFileName() {
SimpleDateFormat simpledateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
Random random = new Random();
return simpledateFormat.format(new Date()) + random.nextInt(10000);
}