1. 程式人生 > 實用技巧 >Javaweb使用getPart來接收表單檔案

Javaweb使用getPart來接收表單檔案

使用getPart接收表單檔案時,注意Tomcat版本要在8之上。

前臺 : form.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/test" method="post" enctype="multipart/form-data">
    請選擇檔案:<input type="file" name="file"><br>
    <input type="submit" value="提交">
</form>
</body>
</html>

後臺:TestServlet

@WebServlet(name = "TestServlet", urlPatterns = "/test")
@MultipartConfig
public class UserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         //獲取檔案,引數為前臺的name
        Part part = request.getPart("file");
        //獲取檔名,獲取到檔名的格式如:a.jpg
        String fileName = part.getSubmittedFileName();
        /**
         擷取檔名的字尾名:
         photo.lastIndexOf('.')的返回值為"."的位置,加1表示字尾名的起始位置。
         photo.substring(photo.lastIndexOf('.')+1),表示從字尾名的起始位置擷取到結束位置。
         * */
        String fileType = fileName.substring(fileName.lastIndexOf('.') + 1);
        //判斷該檔案是不是圖片格式
        if (!("jpg".equalsIgnoreCase(fileType) || "jpeg".equalsIgnoreCase(fileType) || "png".equalsIgnoreCase(fileType))) {
            //不是圖片格式,停止下一步,並將資訊反饋給前臺頁面
            request.setAttribute("msg","上傳的檔案必須為圖片");
            request.getRequestDispatcher(request.getContextPath() + "/form.jsp").forward(request, response);
            return;
        }
        //是圖片型別,構建一個上傳圖片的儲存路徑
        String path = "E:\\upload";
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();  //建立檔案和資料夾
        }
        //將part內容寫到資料夾內,生成一個檔案
        part.write(path + "/" + fileName);
    }
}

String path = "E:\\testPic";設定成本地資料夾路徑與Tomcat伺服器脫離關聯,可以防止檔案丟失。但需要將該資料夾掛載到Tomcat伺服器。

掛載方式:

Eclipse:

1、雙擊整合在Eclipse中的tomcat伺服器

2、點選新增額外的web資源

3、將本地儲存上傳檔案的資料夾新增進來即可!

一定要ctrl + S

IDEA: