上传后台是SpringMVC
上传:
private String path="e:/java/file";
@Transactional
public void save(MultipartFile file) {
//获取客户端上传文件名
String filename = file.getOriginalFilename();
//随机生成一个UUID
String uuid = UUID.randomUUID().toString();
TbFile model = new TbFile();
model.setFilename(filename);
model.setUuid(uuid);
fileDAO.save(model);
File path = new File(this.path);
if(!path.isDirectory()) {
path.mkdir();
}
File saveFile = new File(path, uuid);
try {
file.transferTo(saveFile);
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
}
下载:
public void download(Integer id, HttpServletRequest request, HttpServletResponse response) {
TbFile model = findById(id);
String filename = model.getFilename();
filename = getStr(request, filename);
String uuid = model.getUuid();
File file = new File(path, uuid);
if(file.exists()) {
FileInputStream fis;
try {
fis = new FileInputStream(file);
response.setContentType("application/x-msdownload");
response.addHeader("Content-Disposition", "attachment; filename=" + filename );
ServletOutputStream out = response.getOutputStream();
byte[] buf=new byte[2048];
int n=0;
while((n=fis.read(buf))!=-1){
out.write(buf, 0, n);
}
fis.close();
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String getStr(HttpServletRequest request, String fileName) {
String downloadFileName = null;
String agent = request.getHeader("USER-AGENT");
try {
if(agent != null && agent.toLowerCase().indexOf("firefox") > 0){
//downloadFileName = "=?UTF-8?B?" + (new String(Base64Utils.encode(fileName.getBytes("UTF-8")))) + "?=";
//设置字符集
downloadFileName = "=?UTF-8?B?" + Base64Utils.encodeToString(fileName.getBytes("UTF-8")) + "?=";
}else{
downloadFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return downloadFileName;
}
关键代码都在这里,详细代码访问码云地址:https://gitee.com/macaoying/upload_and_download.git