文件上传和下载
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了文件上传和下载相关的知识,希望对你有一定的参考价值。
一、文件上传(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
以上是关于文件上传和下载的主要内容,如果未能解决你的问题,请参考以下文章