1. 程式人生 > 實用技巧 >上傳檔案(完整程式碼)

上傳檔案(完整程式碼)

package com.zuoguohui.peis.controller;

import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**Controller層程式碼
* @author zuoguohui on 2020/12/19
*/
@RestController
public class FromAction {
@RequestMapping(value = "/upload",method = RequestMethod.POST)
public String upload(@RequestParam("file")

MultipartFile file, HttpServletRequest request, ModelMap model)
throws Exception {

// 判斷提交來的檔案是否為空
if (file.isEmpty()) {
// model.addAttribute("error", "上傳檔案不能為空");
// return "upload";
throw new RuntimeException("file is null");

}
// 獲取檔案所要儲存目錄在伺服器上所對應的實際路徑
String path="C:/image/";
// 組成擁有真實路徑的一個完整的地址字串
String fileUrl = path + "\\" + file.getOriginalFilename();
// 封裝上傳檔名稱到model物件中
model.addAttribute("fileName", file.getOriginalFilename());
// 根據這個完整地址字串,生成提交檔案所要儲存到的目標檔案或目錄的物件
File targetFile = new File(fileUrl);
// 判斷目標檔案或目錄的物件是否已經存在
if (!targetFile.exists()) {
targetFile.mkdirs();
}

// 傳送檔案到目標物件

file.transferTo(targetFile);

System.out.println("已上傳檔案:" + file);
return "ok";
}

@ExceptionHandler
public ModelAndView doException(Exception e,HttpServletRequest request) throws Exception {
Map<String,Object> map = new HashMap<String,Object>();
if (e instanceof MaxUploadSizeExceededException) {
long maxSize = ((MaxUploadSizeExceededException) e)
.getMaxUploadSize();
map.put("error", "上傳檔案太大,不能超過" + maxSize / 1024 + "k");
}else if(e instanceof RuntimeException){
map.put("error", "未選中檔案");
}else{
map.put("error", "上傳失敗");
}
return new ModelAndView("upload",map);

}

@GetMapping("/toFromAtion")
public ModelAndView toFromAtion(ModelAndView modelAndView){
modelAndView.setViewName("form");
return modelAndView;
}
}