servlet檔案上傳

來源:互聯網
上載者:User

標籤:exist   iter   null   status   doget   inf   ext   ipa   port   

Java Servlet 是運行在 Web 服務器或應用伺服器上的程式,它是作為來自 網頁瀏覽器或其他 HTTP 用戶端的請求和 HTTP 伺服器上的資料庫或應用程式之間的中介層。

使用 Servlet可以收集來自網頁表單的使用者輸入,呈現來自資料庫或者其他源的記錄,還可以動態建立網頁。

Servlet實現檔案的上傳和下載實現步驟是差不多的,基本可以分為三個部分:

  1. 建立一個頁面,form提交表單
  2. 寫Servlet程式,實現上傳/下載
  3. 配置web.xml

前期準備:

    匯入commons-fileupload.jar和commons-io.jar兩個jar包,項目匯入路徑:/WEB-INF/lib/。

實現原理:     

A:表單提交有兩種方式GET和POST,前者通常用於提交少量的資料,且安全性較低,POST可以上傳檔案和大量資料,安全性也較高

  1. 首先建立提交表單,jsp檔案和HTML檔案都可以,method方法必須是post,enctype我們需要設定成multipart/form-data
  1. 如果有中文亂碼的問題,我們只需要將charset設定為和編譯器一樣的編碼格式。.
  2. 若需要同時上傳多個檔案,我們需要在下面的程式中再添加<input>表單,然後修改其中的name就可以了。

首先建立表單檔案,HTML或者JSP都可以。

        <h3>檔案上傳:</h3>

        請選擇要上傳的檔案:<br />

         <form action="uploadServlet" method="post" enctype="multipart/form-data">

         <input type="file" name="file" size="50" />

         <br />

         <input type="submit" value="上傳檔案" />

         </form>

然後編寫uploadServlet.java
public class uploadServlet extends HttpServlet {
   /**
     *
     */
    private static final long serialVersionUID = 1L;
    private boolean isMultipart;
    private int maxFileSize = 100*1024 * 1024;
    private int maxMemSize =8*1024 * 1024;
    private File file ;
    private File dtfilepath;
    private Throwable throwable = null;
    public uploadServlet(){
        super();
    }
    /**初始設定檔案上傳路徑*/
    public  void init() throws ServletException{
        Date date = new Date();
        String path = "D:/Dump/" + new SimpleDateFormat("yyyyMMdd").format(date);
        System.out.println("path:" + path);
        dtfilepath = new File(path);
        if(!dtfilepath.exists()){
            dtfilepath.mkdir();
        }
        System.out.println("dtfilepath: " + dtfilepath);
    }
    
    public void doPost(HttpServletRequest request,HttpServletResponse response)
                               throws ServletException, java.io.IOException {
        isMultipart = ServletFileUpload.isMultipartContent(request);
        response.setCharacterEncoding("UTF-8");                         
        if( !isMultipart ){
            return;
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(maxMemSize);
        factory.setRepository(new File("D:/temp"));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax( maxFileSize );
        try{
            List<FileItem> fileItems = upload.parseRequest(request);
            System.out.println("fileItems=" + fileItems);
            Iterator<FileItem> i = fileItems.iterator();
            while ( i.hasNext () )  {
                FileItem fi = (FileItem)i.next();
                System.out.println("fi=" + fi.getSize());
                if(fi.getSize()<=0)
                {
                         response.setStatus(404);
                         throwable.getMessage();
                 }
                /**寫入檔案*/
                 if ( !fi.isFormField())   
                 {
                    String fileName = fi.getName();
                    if( fileName.lastIndexOf("\\") >= 0 ){
                         file = new File( dtfilepath + fileName.substring( fileName.lastIndexOf("\\"))) ;
                         System.out.println("file = " + file);
                    }else{
                         file = new File( dtfilepath + fileName.substring(fileName.lastIndexOf("\\")+1)) ;
                    }
                    fi.write( file ) ;  
                    String pathjsp = dtfilepath.toString();
                    request.getSession().setAttribute("pathjsp", pathjsp);
                    response.sendRedirect("success.jsp");
                 }
          }
       }catch(Exception ex) {
             System.out.println(ex);
       }
   }
   public void doGet(HttpServletRequest request,HttpServletResponse response)
                       throws ServletException, java.io.IOException {
        doPost(request,response);
   }
}

最後配置web.xml

<welcome-file-list>
    <welcome-file>upload.html</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>uploadServlet</servlet-name>
    <servlet-class>uploadDemo.uploadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>uploadServlet</servlet-name>
    <url-pattern>/uploadServlet</url-pattern>
  </servlet-mapping>

最後再編寫Java檔案中調用的success.jsp

<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>上傳成功</title>
</head>
<body>
<p style="color:green"> 檔案上傳成功</p>
<%String pathjsp = (String)request.getSession().getAttribute("pathjsp"); %>
<p>檔案上傳路徑:<%=pathjsp %></p>
</body>
</html>

 

一個基本的檔案上傳就可以了

servlet檔案上傳

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.