1. 程式人生 > >Servlet 通過表單上傳檔案和獲取表單資料的最簡單方式

Servlet 通過表單上傳檔案和獲取表單資料的最簡單方式

注意:本文所描述的方法需要Servlet 3.0 及以上版本的支援。

一、伺服器端Servlet程式碼:

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import
javax.servlet.http.Part; import java.io.IOException; @WebServlet(name = "UploadTestServlet",urlPatterns = {"/upload"}) //下面的註解中location的值為上傳的檔案的臨時存放位置 @MultipartConfig(location = "D://uploadtest") public class UploadTestServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException { System.out.println(request.getParameter("uploaderName")); Part part=request.getPart("file"); //通過表單中的name屬性獲取表單域中的檔案 part.write("D://uploadtest//aaa.txt"); //將檔案移動到特定的磁碟路徑 String fname=part.getSubmittedFileName(); System.out.println("檔名:"
+fname); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }

二、瀏覽器端HTML程式碼

版本1、普通表單提交

<html>
<head>
    <title>上傳頁</title>
</head>
<body>
<form id="uploadForm" enctype="multipart/form-data" method="post" action="/upload">
    <input id="file" type="file" name="file"/>
    <input name="uploaderName" type="text"/>
    <input type="submit" value="提交"/>
</form>
</body>
</html>

版本2、AJAX非同步提交表單

<html>
<head>
    <script type="application/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <title>Title</title>
</head>
<body>
<form id="uploadForm" enctype="multipart/form-data" method="post" action="/upload">
    <input id="file" type="file" name="file"/>
    <input name="uploaderName" type="text"/>
    <button id="upload" value="提交" type="button" onclick="fun();">upload</button>
</form>
<script type="application/javascript">
    function fun() {
        $.ajax({
            url: '/upload',
            type: 'POST',
            cache: false,
            data: new FormData($('#uploadForm')[0]),
            processData: false,
            contentType: false
        }).done(function(res) {
        }).fail(function(res) {});
    }
</script>
</body>
</html>