java spring mvc restful 上传文件
Posted left_
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java spring mvc restful 上传文件相关的知识,希望对你有一定的参考价值。
spring mvc 配置文件
<bean class="com.baiyyy.yfz.core.RestfulHandlerMethodMapping" />
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8" />
<property name="maxUploadSize" value="10485760000" />
<property name="maxInMemorySize" value="40960" />
</bean>
package com.baiyyy.yfz.controller; import java.io.File; import java.io.IOException; import java.util.Date; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.commons.CommonsMultipartFile; import com.baiyyy.yfz.core.BaseController; import com.baiyyy.yfz.util.DateUtil; import com.baiyyy.yfz.util.PictureUploadPath; /** * 基础服务接口 * * @author 左立军 * */ @RestController @RequestMapping("/upload") public class UploadController extends BaseController { /** * 图片路径配置 */ @Autowired private PictureUploadPath pictureUploadPath; @RequestMapping(value = "/picture", consumes = "multipart/form-data", method = RequestMethod.POST) public void picture(@RequestParam("fileUpload") CommonsMultipartFile file) { // 判断文件是否存在 if (!file.isEmpty()) { String path = pictureUploadPath.uploadPicturePath + "/" + DateUtil.convertDateToYYYYMMdd(new Date()) + "/"; File dir = new File(path); if (!dir.exists()) { dir.mkdirs(); } path += file.getOriginalFilename(); File localFile = new File(path); try { file.transferTo(localFile); } catch (IllegalStateException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
以上是关于java spring mvc restful 上传文件的主要内容,如果未能解决你的问题,请参考以下文章
如何将 Oauth2.0 合并到现有的 Java Spring Web MVC 和 REST 项目中?
将 GZIP 压缩与 Spring Boot/MVC/JavaConfig 与 RESTful 结合使用
使用 REST 模板和 JSON 响应格式在 Spring MVC 上返回 Http Status 500