最近总是处理文件上传一块,将写的一些东西记录下来
前端代码如下:其中如果上传文件为图片,记住以下几点。
1、<meta>中一定要加入http-equiv="Content-Type" content="multipart/form-data;
2.请求必须为post
3、form中加入enctype="multipart/form-data"
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="multipart/form-data; charset=utf-8" />
<title>Title</title>
</head>
<body>
<form action="/file.do" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">上传</button>
</form>
</body>
</html>
后代接受代码
@RequestMapping(value = "/file.do", method = RequestMethod.POST)
public String fileUpload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) throws Exception{
String path =request.getSession().getServletContext().getRealPath("");
if(multipartFile.isEmpty()){
System.out.println("没有选择文件");
}else{
String fileName = multipartFile.getOriginalFilename();
File file = new File(path+fileName);
multipartFile.transferTo(file);
System.out.println("文件名:"+fileName);
System.out.println("文件路径:"+file.getPath());
System.out.println("文件后缀名:"+ FilenameUtils.getExtension(multipartFile.getOriginalFilename()));
// file.delete();
}
return "ActivitySystem";
}
至于存放地址,自己根据需要自己修改
19.12-24修改
通过ajax单次和批量上传文件
前段代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片下载或上传</title>
</head>
<body>
封面 :<input type="file" name="sfzfm" id="sfzfm"><br><br>
传文件: <input type="file" name="zj" class="zj">
传文件: <input type="file" name="zj" class="zj">
<button onclick="Text()"> 按下去 </button>
<script src="js/jquery.min.js"></script>
<script type="text/javascript">
function Text() {
var formData = new FormData();
formData.append('sfzzm',document.getElementById("sfzfm").files[0]);
var filess=document.getElementsByName('zj');
for(var i=0;i<filess.length;i++){
console.log(filess[i]);
formData.append('zj',filess[i].files[0]);
}
$.ajax({
url : "/ImageUP",
type : 'POST',
data : formData,
processData : false,
contentType : false,
cache: false
}).done(function(res) { //回调函数
console.log(res)
}).fail(function(res) {
console.log(res)
});
}
</script>
</body>
</html>
后台接口如下:
@PostMapping("/ImageUP")
public Object ImageUP(@RequestParam("sfzzm") MultipartFile me,
@RequestParam("zj") MultipartFile[] me1, HttpServletRequest request){
String path =request.getSession().getServletContext().getRealPath("");
System.out.println(path);
System.out.println(me1);
if(me.isEmpty()){
return "请上传";
}else {
try {
String fileName = me.getOriginalFilename();
File file = new File(path + fileName);
me.transferTo(file);
System.out.println("文件名字 : "+fileName);
}catch (Exception e){
System.out.println(e);
return e;
}
}
return "Image";
}