上傳文件(完整代碼)


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;
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM