1. 程式人生 > 實用技巧 >ajax上傳單個檔案

ajax上傳單個檔案

jsp頁面

<%@ page language="java" pageEncoding="UTF-8"%>
 <!DOCTYPE HTML>
 <html>
   <head>
   <script type="text/javascript" src="./js/jquery-3.5.1.min.js"></script>
  <script type="text/javascript" src="./js/vue.js"></script> 
    <title>檔案上傳</title>  
   </head>   
   <body>
    <input type="file" id="UUploadedFile"  name="fileupload"  onchange="UUploadedFile()">
    <script type="text/javascript">
    function UUploadedFile() {
        var formData = new FormData();
        formData.append('file', $('#UUploadedFile')[0].files[0]);
        $.ajax({
            async: false,//要求同步 不是不需看你的需求
            url : "${pageContext.request.contextPath}/TestuploadFile.do",
            type : 'POST',
            data : formData,
            dataType: "json",
            processData : false,  //必須false才會避開jQuery對 formdata 的預設處理   
            contentType : false,  //必須false才會自動加上正確的Content-Type
            success: function (data) {
                if (data.success ) {
                   alert("上傳完成!");
                }else{
                    alert("上傳失敗!");
                }
            },
        });
    }
    </script>
   </body>
 </html>

  //java後端程式碼

package com.zjn.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
@Controller
public class FileUpload {
	
	@RequestMapping(value = "/TestuploadFile.do")
    @ResponseBody
    public Map<String, Object> TestuploadFile(HttpServletRequest request){
        Map<String, Object> modelMap=new HashMap<String, Object>();
        try {
            MultipartHttpServletRequest mpRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = mpRequest.getFile("file");
            System.out.println("file===="+file);
            long fileSize = file.getSize();//獲取檔案大小
            if (fileSize <= 0) {
                modelMap.put("success", false);
                modelMap.put("MESSAGE", "上傳失敗!上傳的檔案為空!");
                return modelMap;
            }
            if (fileSize > 200 * 1024 * 1024) {//限制上傳檔案大小為200M
                modelMap.put("success", false);
                modelMap.put("MESSAGE", "上傳失敗!上傳的檔案大小超出了限制!");
                return modelMap;
            }
            InputStream in = file.getInputStream();//讀取上傳的檔案流
            OutputStream out = new FileOutputStream("D:/"+file.getOriginalFilename());
            File outFile=new File("D:/"+file.getOriginalFilename());//把檔案輸出到D盤下
            byte[] buffer = new byte[1024];
            int length;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
            in.close();
            out.close();
            if(outFile.exists()){//判斷檔案是否存在
                modelMap.put("success", true);
                modelMap.put("MESSAGE", "上傳完成!");
            }else {
                modelMap.put("success", false);
                modelMap.put("MESSAGE", "上傳失敗!");
                return modelMap;
            }
        }  catch (IOException e) {
            modelMap.put("success", false);
            modelMap.put("MESSAGE", "上傳失敗!");
            return modelMap;
        }
        return modelMap;
    }

}