javaweb的上传和下载

1、下载

@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
}

2、表单上传

表单:

<form action="/upload" method="post" enctype="multipart/form-data">
文件名字:<input name="load" type="file" >
<input type="submit">
</form>

处理:

@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();
}
}

posted @ 2018-09-20 11:09  谁在逆水行舟  阅读(195)  评论(0编辑  收藏  举报