一、下載web
@RequestMapping("/download")
public void download(HttpServletRequest request, HttpServletResponse response) throws IOException{
String filename="大劍.jpg";
InputStream in = request.getServletContext().getResourceAsStream("/"+filename);//放在webapp下面
ServletOutputStream out = response.getOutputStream();
String agent = request.getHeader("User-Agent");//獲取頭文件驗證是不是火狐瀏覽器,實現瀏覽器中文亂碼問題
if (agent.toLowerCase().contains("firefox")) {
filename=new String(filename.getBytes("utf-8"), "iso8859-1");//火狐編碼文件名
}else{
filename=URLEncoder.encode(filename, "utf-8");//ie的編碼
}
response.setHeader("Content-disposition", "attachment;filename="+filename);//設置下載頭
IOUtils.copy(in, out);//使用common-io-apache工具進行copy
}apache
二、表單上傳瀏覽器
表單:app
<form action="/upload" method="post" enctype="multipart/form-data">
文件名字:<input name="load" type="file" >
<input type="submit">
</form>dom
處理:webapp
@ResponseBody
@RequestMapping("/upload")
public void upload(HttpServletRequest request){
DiskFileItemFactory dis = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(dis);
try {
List<FileItem> items = upload.parseRequest(request);
for (FileItem fileItem : items) {
if (!fileItem.isFormField()) {
String filename=fileItem.getName();
int start=0;
if (filename.lastIndexOf("\\")!=-1) {
start=filename.lastIndexOf("\\")+1;
}
filename=filename.substring(start, filename.length());//解決ie瀏覽器路徑問題
filename=UUID.randomUUID()+filename;
String path=request.getServletPath();
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
File newpath=new File(path, year+"\\"+month);
if (!newpath.exists()) {
newpath.mkdirs();
}
System.out.println(newpath);
File file = new File(newpath, filename);
try {
fileItem.write(file);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}工具