一、简介

Spring Boot默认使用springMVC包装好的解析器进行上传

二、代码实现

2.1、from表单

<formmethod="POST"enctype="multipart/form-data"action="/file/upload">文件:<inputtype="file"name="roncooFile"/><inputtype="submit"value="上传"/></form>

2.2、controller

packagecom.example.demo.controller;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.ResponseBody;importorg.springframework.web.multipart.MultipartFile;importjava.io.File;importjava.io.IOException;/***文件上传*@Author:我爱大金子*@Description:文件上传*@Date:Createdin11:082017/6/18*/@Controller@RequestMapping(value="/file")publicclassFileController{privatestaticfinalLoggerlogger=LoggerFactory.getLogger(FileController.class);@RequestMapping(value="/upload")@ResponseBodypublicStringupload(@RequestParam("roncooFile")MultipartFilefile){if(file.isEmpty()){return"文件为空";}//获取文件名StringfileName=file.getOriginalFilename();logger.info("上传的文件名为:"+fileName);//获取文件的后缀名StringsuffixName=fileName.substring(fileName.lastIndexOf("."));logger.info("上传的后缀名为:"+suffixName);//文件上传路径StringfilePath="G:/workspace/file_space/img/";//解决中文问题,liunx下中文路径,图片显示问题//fileName=UUID.randomUUID()+suffixName;Filedest=newFile(filePath+fileName);//检测是否存在目录if(!dest.getParentFile().exists()){dest.getParentFile().mkdirs();}try{file.transferTo(dest);return"上传成功";}catch(IllegalStateExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}return"上传失败";}}

2.3、application.properties

#默认支持文件上传spring.http.multipart.enabled=true#支持文件写入磁盘.spring.http.multipart.file-size-threshold=0#上传文件的临时目录spring.http.multipart.location=G:/workspace/file_space/temp#最大支持文件大小spring.http.multipart.max-file-size=1Mb#最大支持请求大小spring.http.multipart.max-request-size=10Mb

三、测试