文件上传:
注:可以将保存的路径放在配置文件中,使用@Value注解注入;或者写进configuration类中,通过set/get方法获取配置文件中的属性值(这里就不演示了)
//文件的上传
public String upload(MultipartFile file) {
//save.path: E:/test/ 写在配置文件中
@Value("${savePath}")
private String savePath;
File newFile = new File(savePath);
try {
file.transferTo(newFile);
} catch (IOException e) {
e.printStackTrace();
}
return "ok";
}
文件下载:从服务器上获取,你可以将需要下载的文件放在src/resources下
@ApiOperation("模板下载")
@RequestMapping(value = "/download", method = RequestMethod.GET)
public void TemplateDownload(HttpServletResponse response) {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("static/测试.xls");
outputStream = response.getOutputStream();
response.setContentType("application/x-download");
response.setHeader("Content-Disposition", "attachment;filename=" + new String(("测试.xls").getBytes("gb2312"), "iso8859-1"));
IOUtils.copy(inputStream, outputStream);
outputStream.flush();
} catch (IOException e) {
log.error("下载异常:", e);
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
log.error("下载异常:", e);
}
}
}
文件下载:从自己电脑的磁盘的某个位置下载文件
@ApiOperation("文件下载")
@RequestMapping(value = "/discExport", method = RequestMethod.GET)
public void discExport(HttpServletResponse response) {
//获取路径
String fileName = "test.txt";
String exportPath = "E:/test/";
InputStream inputStream = null;
OutputStream outputStream = null;
try {
//File.separator 保证了在任何系统下不会出错。作用相当于 /
inputStream = new FileInputStream(exportPath + File.separator + fileName);
outputStream = response.getOutputStream();
response.setContentType("application/x-download");
response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName).getBytes("gb2312"), "iso8859-1"));
IOUtils.copy(inputStream, outputStream);
outputStream.flush();
} catch (IOException e) {
log.error("下载异常:", e);
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
log.error("下载异常:", e);
}
}
}
转载请注明!!!谢谢