上传⽂件(完整代码)package com.ller;
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");
}
spring framework runtime// 获取⽂件所要保存⽬录在服务器上所对应的实际路径
String path="C:/image/";
// 组成拥有真实路径的⼀个完整的地址字符串
String fileUrl = path + "\\" + OriginalFilename();
// 封装上传⽂件名称到model对象中
model.addAttribute("fileName", OriginalFilename());
// 根据这个完整地址字符串,⽣成提交⽂件所要保存到的⽬标⽂件或⽬录的对象
File targetFile = new File(fileUrl);
/
/ 判断⽬标⽂件或⽬录的对象是否已经存在
if (!ists()) {
targetFile.mkdirs();
}
// 传送⽂件到⽬标对象
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;
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。