1. 程式人生 > >SpringMVC前臺利用ajax和FormData上傳檔案

SpringMVC前臺利用ajax和FormData上傳檔案

前臺的頁面結構及js邏輯

1、 html結構:這裡寫圖片描述

<%--此處必須是multipart/form-data--%>
<form method="post" enctype="multipart/form-data" id="upload">
      <input type="file" name="file" class="uploadfile" id="file">    
      <p><input type="button" value="上傳" class="addbtn"></p>
</form>

2、ajax內容(此處運用jquery):

$(".addbtn").click(function () {
        //獲取input:type='file'選中檔案的內容
        var file = $("#file")[0].files[0];

        if ($("#file").val() == "") {
            alert("請選擇上傳檔案");
        } else {
            var formData = new FormData();

            //此處將所要傳遞的資料append到formData中
formData.append("fileinfo", file); $.ajax({ url: "/uploadFile", type: "POST", data: formData, processData: false, //必不可缺 contentType: false, //必不可缺 success: function
(e) {
alert("檔案上傳成功"); $("#file").val() == ""; } }) } });

後臺的頁面結構及js邏輯

1、pom.xml中的配置(在maven中下載所需要的包)

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.0</version>
    <scope>provided</scope>
</dependency>

2、SpringMVC的Controller中的內容

//    上傳檔案
    @ResponseBody
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public void uploadFile(@RequestParam(value = "fileinfo", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        //上傳檔案的路徑
        String path = FileTools.getFileInfo(request, response, file);
    }

3、工具類裡面的內容

    // 自定義上傳檔案儲存目錄
    private static final String UPLOAD_DIRECTORY = "upload";

    //MultipartFile上傳檔案
    public static String getFileInfo(HttpServletRequest request, HttpServletResponse response, MultipartFile file) {
        String filePath = new String();
        String uploadPath = request.getSession().getServletContext().getRealPath("./") + UPLOAD_DIRECTORY;

        // 如果目錄不存在則建立
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        //判斷檔案是否為空
        if (!file.isEmpty()) {
            try {
                //檔案的儲存路徑
                filePath = request.getSession().getServletContext().getRealPath("/") + UPLOAD_DIRECTORY + File.separator + file.getOriginalFilename();

                //轉存檔案
                file.transferTo(new File(filePath));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return filePath;
    }//函式結束符

此文章僅限自己的筆記而已,其中有些術語可能不太準確,只供參考,如有問題歡迎賜教!