码迷,mamicode.com
首页 > Web开发 > 详细

文件上传和下载

时间:2017-03-17 13:34:36      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:fileupload   filedoanload   

一、文件上传(commons-fileupload-1.2.1.jar和commons-io-2.0.jar)

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
fileItemFactory.setSizeThreshold(1024*10);
fileItemFactory.setRepository(new File("d:\\tmp"));
ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
servletFileUpload.setSizeMax(1024*1000);
try {
List<FileItem> lists = servletFileUpload.parseRequest(httpServletRequest);
if(lists!=null){
for(FileItem fileItem : lists){
if(fileItem.isFormField()){
String fieldName = fileItem.getFieldName();
String fieldValue = fileItem.getString();
}else{
InputStream inputStream = fileItem.getInputStream();
String fileName = fileItem.getName();
byte[] b = new byte[1024];
int len=0;
FileOutputStream fileOutputStream = new FileOutputStream("d:\\"+fileName);
while((len=inputStream.read(b))!=-1){
fileOutputStream.write(b, 0, len);
}
fileOutputStream.close();
inputStream.close();
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}

文件下载

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse.setContentType("application/x-msdownload");
String fileName = "爱情码头郑源.mp3";
httpServletResponse.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
OutputStream outputStream = response.getOutputStream();
InputStream inputStream = new FileInputStream("F:\\音乐\\" + fileName);
byte[] b = new byte[1024];
int len = 0;
while((len=inputStream.read(b))!=-1){
outputStream.write(b, 0, len);
}
inputStream.close();
}


本文出自 “11137669” 博客,请务必保留此出处http://11147669.blog.51cto.com/11137669/1907597

文件上传和下载

标签:fileupload   filedoanload   

原文地址:http://11147669.blog.51cto.com/11137669/1907597

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!