前端代码:
<input type="file" id="file" name="file"/>
使用ajax将其传给后台(ajax代码):
```css
file.onchange = function(){
var formData = new FormData();
var temp = file.files[0];
if (temp){
formData.append('file',temp)
img.src = window.URL.createObjectURL(temp)
$.ajax({
url:"/uploadImg/"+id,
type:"POST",
data: formData,
dataType : "json",
processData: false, // 告诉jQuery不要去处理发送的数据
contentType: false, // 告诉jQuery不要去设置Content-Type请求头
success: function(result){
//alert(result);
window.location.reload();
}
});
}
后台Java代码:
```java
@RequestMapping(value = "/uploadImg/{
id}", method = RequestMethod.POST)
public String upload(@RequestParam("file")MultipartFile file,Model model,
@PathVariable("id") int id,
HttpServletRequest request) {
if (file.isEmpty()) {
return "上传失败,请选择文件";
}
String fileName = file.getOriginalFilename();
String newName = null;
System.out.println(fileName);
// 生成uuid作为文件名称
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
/*// 获得文件类型(可以判断如果不是图片,禁止上传)
String contentType = user.getFile().getContentType();*/
// 获得文件后缀名
String suffixName = fileName
.substring(fileName.indexOf("/") + 1);
// 得到 文件名
newName = uuid + "." + suffixName;
File dest = null;
String path = null;
String os = System.getProperty("os.name");
System.out.println(os);
if (os.toLowerCase().startsWith("win")) {
path = "E:"+File.separator+"test"+File.separator;
System.out.println(path);
dest= new File(path + newName);
}else {
path = "/webapps/img/";
dest= new File(path + newName);
}
model.addAttribute("src","img/"+newName);
try {
file.transferTo(dest);
//把评论插入数据库
Comment comment=new Comment();
comment.setImages(newName);//此处只给出了images属性
commentMapper.insert(comment);
return JSON.toJSONString("上传成功!");
} catch (IOException e) {
return JSON.toJSONString("上传失败!");
}
}
此时,我们便可以进行图片上传了!