commons-fileupload实现文件上传下载
生活随笔
收集整理的這篇文章主要介紹了
commons-fileupload实现文件上传下载
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
commons-fileupload是Apache提供的一個實現文件上傳下載的簡單,有效途徑,需要commons-io包的支持,本文是一個簡單的示例
上傳頁面,注意設置響應頭
<body><center><h1>文件上傳頁面</h1><hr><form action="${pageContext.request.contextPath }/servlet/UploadServlet" method="post" enctype="multipart/form-data">選擇文件:<input type="file" name="file1"/><br>描述信息:<textarea rows="5" cols="45" name="discription"></textarea><br><input type="submit" value="上傳"/></form></center></body>上傳的servlet
//上傳文件String upload=this.getServletContext().getRealPath("WEB-INF/upload");String temp=this.getServletContext().getRealPath("WEB-INF/temp");Map pmap=new HashMap();//get client IP addresspmap.put("ip", request.getRemoteAddr());DiskFileItemFactory factory=new DiskFileItemFactory();//設定內存緩沖區大小 Set the memory buffer sizefactory.setSizeThreshold(1024*100);//指定臨時文件目錄 Specifies the directory for temporary filesfactory.setRepository(new File(temp));ServletFileUpload fileUpload=new ServletFileUpload(factory);fileUpload.setHeaderEncoding("utf-8");fileUpload.setFileSizeMax(1024*1024*100);fileUpload.setSizeMax(1024*1024*200);//set form style enctype="multipart/form-data"if(!fileUpload.isMultipartContent(request)){throw new RuntimeException("請使用正確的表單進行上傳");}//解析requesttry {List<FileItem> list= fileUpload.parseRequest(request);//遍歷listfor(FileItem item:list){if(item.isFormField()){String name=item.getFieldName();String value=item.getString("utf-8");pmap.put(name, value);}else{String realname=item.getName();String arry[]=realname.split("\\\\");realname=arry[arry.length-1];System.out.println(realname);String uuidName=UUID.randomUUID().toString()+"_"+realname;pmap.put("realname", realname);pmap.put("uuidname", uuidName);InputStream in=item.getInputStream();String hash=Integer.toHexString(uuidName.hashCode());String savepath="/WEB-INF/upload";for(char c:hash.toCharArray()){upload+="/"+c;savepath+="/"+c;}new File(upload).mkdirs();pmap.put("savepath", savepath);OutputStream out=new FileOutputStream(new File(upload,uuidName));IOUtils.In2Out(in, out);IOUtils.close(in, out);item.delete();}}} catch (Exception e) {// TODO 自動生成的 catch 塊e.printStackTrace();}//向數據庫中插入數據Resourse r=new Resourse(); try {BeanUtils.populate(r, pmap);String sql="insert into netdisk values(null,?,?,?,?,null,?)";QueryRunner runner=new QueryRunner(DaoUtils.getSource());runner.update(sql,r.getUuidname(),r.getRealname(),r.getSavepath(),r.getIp(),r.getDescription());} catch (Exception e) {// TODO 自動生成的 catch 塊e.printStackTrace();} //重定向回主頁response.sendRedirect(request.getContextPath()+"/index.jsp");為防止重名,所以使用了UUIDNAME,把文件上傳到web-inf/upload文件夾下,并且將路徑與文件名保存到數據庫中,上傳功能完成
下載實現
下載頁面
<body><center><h1>下載列表</h1><hr><c:forEach items="${requestScope.list }" var="r"><h2>文件名:${r.realname }<br></h2>上傳時間:${r.uploadtime }<br>上傳者IP:${r.ip }<br>描述信息:${r.description }<br><a href="${pageContext.request.contextPath }/servlet/DownServlet?id=${r.id}">下載</a><br><hr></c:forEach></center></body>下載實現
response.setContentType("text/html;charset=utf-8");//獲取IDString id=request.getParameter("id");//根據ID查找資源String sql="select * from netdisk where id=?";Resourse r=null;QueryRunner runner=new QueryRunner(DaoUtils.getSource());try {r= runner.query(sql, new BeanHandler<Resourse>(Resourse.class), id);} catch (SQLException e) {// TODO 自動生成的 catch 塊e.printStackTrace();}if(r==null){response.getWriter().write("找不到該資源!!!!");return;}else{//指定響應頭response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(r.getRealname(),"UTF-8"));response.setContentType(this.getServletContext().getMimeType(r.getRealname()));String filePath=this.getServletContext().getRealPath(r.getSavepath()+"/"+r.getUuidname());InputStream in=new FileInputStream(filePath);OutputStream out=response.getOutputStream();IOUtils.In2Out(in, out);IOUtils.close(in, null);}上傳下載完成,注意,下載時一定要指定兩個響應頭
IO工具類
public class IOUtils {private IOUtils() {}public static void In2Out(InputStream in,OutputStream out) throws IOException{byte [] bs = new byte[1024];int i = 0;while((i=in.read(bs))!=-1){out.write(bs,0,i);}}public static void close(InputStream in,OutputStream out){if(in!=null){try {in.close();} catch (IOException e) {e.printStackTrace();}finally{in = null;}}if(out!=null){try {out.close();} catch (IOException e) {e.printStackTrace();}finally{out = null;}}} }完成
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的commons-fileupload实现文件上传下载的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Django搭建简易博客
- 下一篇: 【每日SQL打卡】