//将文件写入到本地(文件上传)
public String feedbackFileUpload(MultipartFile file){
//文件名
String fileName = file.getOriginalFilename();
//生成时间戳
long currentDate = System.currentTimeMillis();
int index = fileName.lastIndexOf(".");
//文件后缀
String suffix = fileName.substring(index + 1);
//文件路径
String filePath = dir+ "/" + "wood" +"/" + "KJLFeedbackFileUpload" +"/" + currentDate+"."+suffix ;
FileOutputStream out = null;
try {
byte[] bytes = file.getBytes();
File newFile = new File(filePath);
if (!newFile.exists()) {
newFile.getParentFile().mkdirs();
//创建文件
newFile.createNewFile();
}
out = new FileOutputStream(newFile);
out.write(bytes);
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return filePath;
}
//去指定路径下下载文件
public void download(HttpServletResponse response, String filePath){
File file = new File(filePath);
// 取得文件名。
String fileName = file.getName();
InputStream fis = null;
try {
fis = new FileInputStream(file);
response.reset();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition",
"attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso8859-1"));
response.setHeader("Content-Length", String.valueOf(file.length()));
byte[] b = new byte[1024];
int len;
while ((len = fis.read(b)) != -1) {
response.getOutputStream().write(b, 0, len);
}
response.flushBuffer();
fis.close();
}catch (IOException e) {
throw new RuntimeException(e);
}
}
java根据路径上传下载文件
最新推荐文章于 2024-07-20 03:18:05 发布