一、下载文件
public void downloaddownfiles(HttpServletResponse response, String filepath) {
try {
File file = new File(filepath);//filepath为绝对路径,包括服务器路径,项目中文件夹路径和文件名称(文件名称包括后缀名)
// 取得文件名。
String filename = file.getName();
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(filepath));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
String newfilename=URLEncoder.encode(filename, "UTF-8");
response.addHeader("Content-Disposition", "attachment;filename=" + newfilename);
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
二、更新文件
注:只更新图片内容名称不变,更新同类型文件
public void fileUpdate(@RequestParam("file") MultipartFile file,HttpServletRequest request,HttpServletResponse response) throws Exception {
String filename = request.getParameter("name");//服务器中原图片的文件名,从前端页面传入后台
String filePath="";
if (!file.isEmpty()) {
try {
filePath= request.getSession().getServletContext().getRealPath("/")+ "/file/"+ filename;
String filerootpath = request.getSession().getServletContext().getRealPath("/")+ "/file/";
File filerootpathdic = new File(filerootpath);
if(!filerootpathdic.exists()){
filerootpathdic.mkdirs();
}
file.transferTo(new File(filePath));
} catch (Exception e) {
e.printStackTrace();
}
}
}
三、删除文件
public Boolean delete(String name,HttpServletRequest request ){
String path = request.getSession().getServletContext().getRealPath("/");
File file = new File(path+"/file/"+name);//name为带后缀的文件名
file.delete();
return true;
}
欧拉.............