Spring boot 基于ajax 文件上传下载
2018-06-07 本文已影响0人
离别刀
8142826.png
1.配置静态文件访问路径
@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/images/**").addResourceLocations("classpath:/images/");
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("/view/**").addResourceLocations("classpath:/view/");
super.addResourceHandlers(registry);
}
}
2.配置文件上传大小
@Configuration
public class BeanConfig {
@Bean
public MultipartConfigElement init(){
MultipartConfigFactory factory = new MultipartConfigFactory();
//文件最大
factory.setMaxFileSize("102400KB"); //KB,MB
/// 设置总上传数据总大小
factory.setMaxRequestSize("102400KB");
return factory.createMultipartConfig();
}
}
3.多文件上传接口,下载文件接口
import com.example.demo.util.FileUploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;
@RequestMapping("/file")
@Controller
public class FileCtrl {
private static final String uploadPath = "D:/Images/";
@Autowired
private FileUploadUtil fileUploadUtil;
@RequestMapping("/images")
public String uploadTest() {
return "images";
}
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public List<Map<String, Object>> uploadFile(HttpServletRequest request, @RequestParam MultipartFile[] files) {
return fileUploadUtil.upload(files, uploadPath);
}
@RequestMapping("/load")
public ResponseEntity<byte[]> fileDownLoad(@RequestParam("fileName") String fileName) throws Exception{
String filePath= uploadPath+fileName;
InputStream in=new FileInputStream(new File(filePath));
byte[] body=null;
body=new byte[in.available()];
in.read(body);
fileName=new String(fileName.getBytes("gbk"),"iso8859-1");
HttpHeaders headers=new HttpHeaders();
headers.add("Content-Disposition", "attachment;filename="+fileName);
HttpStatus statusCode = HttpStatus.OK;
ResponseEntity<byte[]> response=new ResponseEntity<byte[]>(body, headers, statusCode);
return response;
}
}
4.文件上传工具类
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.*;
@Component
public class FileUploadUtil{
public List<Map<String,Object>> upload(MultipartFile[] fileList,String uploadPath) {
List<Map<String, Object>> list = new ArrayList<>();
if (fileList != null) {
for (MultipartFile file : fileList) {
long fileSize = file.getSize();
String oriName = file.getOriginalFilename();
String newName = UUID.randomUUID() + "." + StringUtils.substringAfterLast(oriName, ".");
try {
//method1(file,uploadPath,newName);
method2(file,uploadPath,newName);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("copyInputStreamToFile error.");
}
Map<String, Object> res = new HashMap<>();
res.put("fileSize", fileSize);
res.put("oriName", oriName);
res.put("imageName", newName);
list.add(res);
}
}
return list;
}
//基于spring接口文件保存
private void method1(MultipartFile file,String path,String fileName) throws IOException {
File localFile = new File(path);
if (!localFile.exists()) {
localFile.mkdir();
}
file.transferTo(new File(path, fileName));
}
//基于apache文件保存
private void method2(MultipartFile file,String path,String fileName) throws IOException {
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path, fileName));
}
}
5.文件上传页面
<html lang="zh-CN">
<head>
<meta charset="UTF-8"/>
<script src="/static/jquery-1.8.3.min.js"></script>
<script src="/static/ajaxfileupload.js"></script>
</head>
<body>
<input id="upload" type="file" name="files" multiple="multiple" value="上传文件" onchange="fileChange()"/>
<hr/>
<div id="images">
<img src=""/>
</div>
</body>
<script type="text/javascript">
function fileChange(){
debugger;
var fielId= event.target.id;
$.ajaxFileUpload({
url:'/file/upload',
type: 'post',
secureuri:false,
fileElementId:fielId,//文件选择框的id属性
dataType: 'json', //json
success: function(res){
console.log(res);
$(res).each(function(index,data){
var image="<img with='300' height='300' src='/file/load?fileName=";
image+= data.imageName;
image+= "'/>";
$("#images").append(image);
});
},
error:function(XMLHttpRequest, textStatus, errorThrown){
alert('上传失败!');
}
});
}
</script>
</html>