Servlet的檔案上傳與下載

來源:互聯網
上載者:User

工程目錄結構:

檔案上傳

檔案上傳用到了commons-fileupload-1.2.1.jar和commons-io-1.4.jar兩個jar包。指定將檔案上傳到伺服器的store目錄下。

fileupload.jsp:

<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%><html><head><title>Insert title here</title></head><body><form action="upload" method="post" enctype="multipart/form-data">姓名:<input type="text" name="username" size="14"><br>檔案:<input type="file" name="file1" size="14"><input type="submit" value="上傳"></form></body></html>

這裡需要注意兩點:第一method方法必須修改為post。第二為form標籤添加enctype屬性,且值必須為multipart/form-data。<form>標記的enctype屬性的預設值為"application/x-www-form-urlencoded",也就是說若未明確添加enctype屬性,則使用這個預設值。enctype屬性用於指定表單資料的MIME類型,預設值表示表單資料會採用“名字=值”的形式。而對於檔案上傳,這裡必須取值“multipart/form-data”。

FileUploadServlet.java

public class FileUploadServlet extends HttpServlet {public void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("UTF-8");DiskFileItemFactory factory=new DiskFileItemFactory();ServletFileUpload sfu=new ServletFileUpload(factory);try {List<FileItem> items=sfu.parseRequest(request);for(int i=0;i<items.size();i++){FileItem item=items.get(i);if(item.isFormField()){//普通表單域String paraName=item.getFieldName();String paraValue=item.getString();}else{//檔案域ServletContext ctx=getServletContext();String path=ctx.getRealPath("store");String fileName=item.getName();fileName=fileName.substring(fileName.lastIndexOf("/")+1);File file=new File(path+"/"+fileName);item.write(file);}}} catch (FileUploadException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}}}

點擊上傳,然後到伺服器的應用下的store目錄下可看到剛才上傳的檔案。

檔案下載

filedownload.jsp:

<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%><html><head><title>Insert title here</title></head><body><form action="download">輸入要下載的檔案名稱:<br><input type="text" name="filename"><input type="submit" value="開始下載"></form></body></html>

我們輸入剛才上傳的web.jpg檔案:

FileDownloadServlet.java:

public class FileDownloadServlet extends HttpServlet {public void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("UTF-8");String filename=request.getParameter("filename");System.out.println(filename);response.setContentType("application/force-download");response.setHeader("Content-Disposition","attachment;filename="+filename);ServletContext ctx=getServletContext();InputStream in=ctx.getResourceAsStream("store/"+filename);System.out.println(in==null);OutputStream out=response.getOutputStream();int hasRead=0;byte[] buffer=new byte[1024];while((hasRead=in.read(buffer))!=-1){out.write(buffer,0,hasRead);}out.close();in.close();}}

點擊開始下載,可以看到瀏覽器彈出提示下載框。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.