文件上传maven依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
Spring MVC bean配置
<!-- 文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="5120000"></property>
<property name="uploadTempDir" value="/upload"></property>
</bean>
/**
* Created by cody on 2016/12/26.
*
* 文件上传Controller
*
*
*/
@Controller
@RequestMapping("upload")
public class UploadController {
private static final Logger logger = Logger.getLogger(UploadController.class);
@PostConstruct
public void init(){
logger.debug("----------- UploadController init() ----------");
}
@RequestMapping(value = "image",method = RequestMethod.POST)
@ResponseBody
public Object fileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request,
@Autowired ApiMessage apiMessage){
if(file != null && !file.isEmpty()){
String originalFilename = file.getOriginalFilename();
logger.debug(originalFilename);
//文件保存路径
File outPath = new File(request.getServletContext().getRealPath("/"),"fileDir");
if(!outPath.exists() || !outPath.isDirectory()){
outPath.mkdirs();
}
//保存的文件dest File
File outFile = new File(outPath,file.getOriginalFilename());
logger.debug(outFile.getAbsolutePath());
try {
//从缓存文件复制到目标文件
file.transferTo(outFile);
//保存文件信息,返回ID
} catch (IOException e) {
e.printStackTrace();
logger.debug(e);
}
}
return apiMessage;
}
}