上传文件(完整代码)


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