springboot里表单里单个文件上传
表单里单个文件上传类似于现实中,给朋友发送qq邮件等类似情景
@Controller public class UpLoadController { //创建格式化日期对象 SimpleDateFormat sdf=new SimpleDateFormat(); @RequestMapping("/index1") public String index(){ return "index"; } @RequestMapping("/upload") @ResponseBody public String upload(MultipartFile file,HttpServletRequest request){ //MultipartFile是spring提供的一个接口,用来接收multipart/form-data类型 String format=sdf.format(new Date()); String path=request.getServletContext().getRealPath("/file"); //创建一个路径下文件夹对象 File folder=new File(path); 判断文件是否真正存在,如果不存在,创建一个 if(!folder.exists()){ //mkdir()只能创建单层目录文件夹 //mkdirs()能创建多层目录文件夹 folder.mkdirs(); } String oldName=file.getOriginalFilename(); String newName=UUID.randomUUID().toString()+oldName.substring(oldName.lastIndexOf(".")); try { file.transferTo(new File(folder,newName)); //request.getSchema()可以返回当前页面使用的协议,http 或是 https String url=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/img"+format+newName; System.out.println(url); return "success"; }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "error"; }
此代码是controller层的,整体能运行成功,如有注释或者别的方面错了可以留言