实现单个文件上传
jsp页面
<div class="modal-body">
<form id="doadd" enctype="multipart/form-data" class="form-horizontal">
<div class="form-group">
<label for="img_name" class="col-sm-2 control-label">图片名称</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="img_name" placeholder="请输入图片名称">
</div>
</div>
<div class="form-group">
<label for="img_type" class="col-sm-2 control-label">图片类型</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="img_type" placeholder="请设置图片类型">
</div>
</div>
<div class="form-group">
<label for="img_url" class="col-sm-2 control-label">选择图片</label>
<div class="col-sm-10">
<!-- 必须加name属性,不然会报错 -->
<input style="margin-top: 6px;" type="file" name="myfile">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" id="addBTN" class="btn btn-default">立即提交</button>
</div>
</div>
</form>
</div>
ajax方法
$("#addBTN").on("click", function() {
var formData = new FormData($('#doadd')[0]);
$.ajax({
type: "post",
url: "${path}/image/doadd",
data: formData, // 得到form表单里面的数据
processData: false, // 不指定编码方式(默认指定编码 urlencode)
contentType: false, // 不处理数据(默认处理数据:name=lxx &age=18)
dataType: "json", // 指定后台传过来的数据是json格式
success: function(data){
if(data == true){
alert("添加成功!");
location.reload();
}else{
alert("添加失败!");
location.reload();
}
},
error: function(err){
alert("数据异常!");
break;
}
})
});
controller层
@PostMapping("doadd")
@ResponseBody
public boolean doadd(MultipartFile myfile, Image image, HttpServletRequest request) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
// 得到当前时间,如:20190823155059718
String nowdate = sdf.format(new Date());
// 设置上传路径
String path = "F:\\Program Files (x86)\\upload\\images";
// 得到上传的文件以.开始的后缀名
String lastIndexOf = myfile.getOriginalFilename().substring(myfile.getOriginalFilename().lastIndexOf("."));
// 得到新文件名,如:20190823155619838.jpg
String newFileName = nowdate + lastIndexOf;
// 得到文件的全路径,如:F:\\Program Files (x86)\\upload\\20190823155619838.jpg
path += "\\" + newFileName;
// 拷贝输入流到文件夹中
FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(path));
// 把路径存到数据库中
String img_url = "/upload/images/" + newFileName;
image.setImg_url(img_url);
if (image != null) {
i = imageService.add(image);
}
if (i > 0) {
flag = true;
}
} catch (IOException e) {
e.printStackTrace();
}
return flag;
}