文件上传及下载:
控制器或服务层方法
public class FileUpload {
@Value("${filePath}")
//文件路径夹
private String filePath;
@ApiOperation("单上传文件")
@PostMapping("/upload")
public Object singleFileUpload(MultipartFile file, HttpServletRequest request) throws IOException {
String fileName = file.getOriginalFilename();
File fileDir = new File(filePath);
if(!fileDir.exists()){
fileDir.mkdir();
}
fileDir.getAbsolutePath();
file.transferTo(new File(fileDir.getAbsolutePath(),fileName));
return request.getRequestURI() + fileName;
}
@PostMapping("/multiFileUpload")
public Object multiFileUpload(MultipartFile[] files,HttpServletRequest request){
StringBuilder builder = new StringBuilder();
for (MultipartFile file : files){
String fileName = file.getOriginalFilename();
File fileDir = new File(filePath);
if(!fileDir.exists()){
fileDir.mkdir();
}
fileDir.getAbsolutePath();
try {
file.transferTo(new File(fileDir.getAbsolutePath(),fileName));
} catch (IOException e) {
continue;
}
builder.append(request.getRequestURI() + fileName + ",");
}
if(builder.length()>1){
builder = builder.deleteCharAt(builder.length()-1);
}
return builder;
}
@RequestMapping("/download")
public Object contactTemp(HttpServletRequest request, HttpServletResponse response,String fileName) throws Exception{
String temp = tempPath + fileName;
logger.info(temp);
File file = new File(temp);
if (file.exists()) {
response.setContentType("application/force-download");// 设置强制下载不打开
response.setHeader("Content-Disposition",
"attachment;filename=" + new String("contact.xls".getBytes("UTF-8"),"iso-8859-1"));
response.setHeader("Content-Type", "application/octet-stream");
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
return "下载成功";
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return "下载失败";
}
}
文件夹映射:
@Configuration
public class FileUrl extends WebMvcConfigurerAdapter {
@Value("${filePath}")
private String filePath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//和页面有关的静态目录都放在项目的static目录下
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
//上传的图片在D盘下的目录下,访问路径如:http://localhost:8080/d3cf0281-bb7f-40e0-ab77-406db95ccf2c.jpg
//其中addResourceHandler中表示访问的前缀。addResourceLocations中是文件真实的存储路径
System.out.println(filePath);
registry.addResourceHandler("/**").addResourceLocations("file:" + filePath);
//允许swagger访问静态页面
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
}
}
docker部署时需进行文件夹映射,多文件夹映射命令:
docker run -p 16888:16888 -v /root/config:/config -v /root/config/temp:/root/config/temp -v /home/fdfs/storage/data:/home/fdfs/storage/data --name app app:0.0.1-SNAPSHOT
-v 操作为文件夹映射
注:文件下载时如果可以通过浏览器直接下载而不是解析后加载的可以直接使用
window.location.href="接口地址"
进行外部资源调用。
注:文件映射时会影响static下的html、swagger-ui.html等静态资源访问,如果出现问题请将配置更改为:
registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/").addResourceLocations("classpath:/resources/").addResourceLocations("classpath:/static/").addResourceLocations("classpath:/public/").addResourceLocations("file:" + filePath);
即可解决以上所述问题
文件上传html代码:
写法一:直接form表单提交
<form enctype="multipart/form-data" action="/upload" method="POST">
<input id="file" type="file"/>
<button id="uploadimg" type="button">uploadimg</button>
</form>
写法而:通过ajax进行form表单提交
var formData = new FormData();
//单文件,多文件时此处应用for玄幻
formData.append("file", document.getElementById("file").files[0]);
$.ajax({
url: "/upload",
type: "POST",
data: formData,
/**
*必须false才会自动加上正确的Content-Type
*/
contentType: false,
/**
* 必须false才会避开jQuery对 formdata 的默认处理
* XMLHttpRequest会对 formdata 进行正确的处理
*/
processData: false,
success: function (data) {
if (data) {
layer.msg("上传成功!");
}
}
});