1. 程式人生 > >servlet3.0文件上傳

servlet3.0文件上傳

servlet3.0文件上傳

1.瀏覽器端:選擇圖片、提交表單,同時將圖片發送給服務器
<form action=”” method=”post” enctype=”multipart/form-data”>
<input type=”file” name=”image”>
<input type=”submit”>
上傳的內容,都在請求體中。
2.服務器端:
1)手動獲得請求體,需要手動解析。request.getInputStream()
2)使用servlet3.0
3)第三方工具 – apache-commons-fileupload
4)struts2
技術分享圖片

@WebServlet("/FileUploadServlet")
@MultipartConfig        //表示支持文件上傳,否則獲得null

public class FileUploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
    //1 普通字段
    String username = request.getParameter("username");
    System.out.println(username);

    //2 上傳字段
    Part part = request.getPart("image");
    //2.1 獲得文件名   
    // * IE         --> C:\Users\liangtong\Desktop\heima.txt
    // * 其他瀏覽器  --> heima.txt
    String contentDisposition = part.getHeader("Content-Disposition");
    System.out.println(contentDisposition);
    // * 截取文件名
    int start = contentDisposition.indexOf("filename=") + 10;
    int end = contentDisposition.length() - 1;
    String fileName = contentDisposition.substring(start, end);

    // * 瀏覽器兼容  -- lastIndexOf() 如果沒有獲得返回 -1
    fileName = fileName.substring( fileName.lastIndexOf("\\") + 1);

    System.out.println(fileName);

    //2.2 獲得上傳文件內容
    InputStream is = part.getInputStream();

    //2.3 將流寫入到服務器文件中
    // * 上傳目錄
    String dir = this.getServletContext().getRealPath("/WEB-INF/upload");
    File file = new File(dir , fileName);

    // * 流的對拷
    FileOutputStream out = new FileOutputStream(file);

    byte[] buf = new byte[1024];
    int len = -1;
    while( (len = is.read(buf)) != -1 ){
        out.write(buf, 0, len);
    }

    out.close();
    is.close();

}

protected void doPost(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
    doGet(request, response);
}

servlet3.0文件上傳