SpringMVC實現多檔案上傳原始碼

Evan1024發表於2024-03-08
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/file")
public class UploadController {


    //位元組輸入流檔案上傳
    @RequestMapping("/upload")
    public String upload (@RequestParam("file") CommonsMultipartFile[] files, HttpServletRequest request) {

        for (int i = 0; i < files.length; i++) {
            System.out.println("fileName---------->" + files[i].getOriginalFilename());

            if (!files[i].isEmpty()) {
                int pre = (int) System.currentTimeMillis();
                try {
                    //拿到輸出流,同時重新命名上傳的檔案
                    FileOutputStream os = new FileOutputStream("H:/" + new Date().getTime() + files[i].getOriginalFilename());
                    //拿到上傳檔案的輸入流
                    FileInputStream in = (FileInputStream) files[i].getInputStream();

                    //以寫位元組的方式寫檔案
                    int b = 0;
                    while ((b = in.read()) != -1) {
                        os.write(b);
                    }
                    os.flush();
                    os.close();
                    in.close();
                    int finaltime = (int) System.currentTimeMillis();
                    System.out.println(finaltime - pre);

                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("上傳出錯");
                }
            }
        }
        return "/success";
    }


    //包裝類實現檔案上傳
    @RequestMapping("/upload2")
    public String upload2(HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException {
        //建立一個通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //判斷 request 是否有檔案上傳,即多部分請求
        if (multipartResolver.isMultipart(request)) {
            //轉換成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            //取得request中的所有檔名
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                //記錄上傳過程起始時的時間,用來計算上傳時間
                int pre = (int) System.currentTimeMillis();
                //取得上傳檔案
                MultipartFile file = multiRequest.getFile(iter.next());
                if (file != null) {
                    //取得當前上傳檔案的檔名稱
                    String myFileName = file.getOriginalFilename();
                    //如果名稱不為“”,說明該檔案存在,否則說明該檔案不存在
                    if (myFileName.trim() != "") {
                        System.out.println(myFileName);
                        //重新命名上傳後的檔名
                        String fileName = "demoUpload" + file.getOriginalFilename();
                        //定義上傳路徑
                        String path = "H:/" + fileName;
                        File localFile = new File(path);
                        file.transferTo(localFile);
                    }
                }
                //記錄上傳該檔案後的時間
                int finaltime = (int) System.currentTimeMillis();
                System.out.println(finaltime - pre);
            }

        }
        return "/success";
    }

    @RequestMapping("/toUpload")
    public String toUpload() {

        return "/upload";
    }

} 

相關文章