maven依赖
<!-- 文件上传组件 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> </dependency>
spring引入配置文件
<context:property-placeholder location="classpath:config/sysconfig.properties" />
sysconfig.properties文件
TRACKER_PATH=classpath:config/tracker.conf
IMAGE_DOMAIN=http://*.*.*.*/
tracker.conf文件
tracker_server=*.*.*.*:22122
spring中添加bean
<!--文件上传解析器 id不能变--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"></property> <!--设定文件最大上传值5MB 5*1024*1024--> <property name="maxUploadSize" value="5242800"></property> </bean>
文件上传
@RestController @RequestMapping("/uploadfile") public class UploadController { /* * 文件上传 * */ @Value("${TRACKER_PATH}") private String TRACKER_PATH; @Value("${IMAGE_DOMAIN}") private String IMAGE_DOMAIN; @RequestMapping(value = "/upload",method = RequestMethod.POST) public Result upload(MultipartFile file) throws Exception{ //获取文件名 String originalFilename = file.getOriginalFilename(); //截取后缀 //originalFilename.substring(originalFilename.lastIndexOf('.'),originalFilename.length()); //获取扩展名 String filenameExtension = StringUtils.getFilenameExtension(originalFilename); //获取文件的字节数组 byte []bytes=file.getBytes(); //FastDFS //tracker配置信息 文件本地路径 String[] upload = UploadUtil.upload(TRACKER_PATH, bytes, filenameExtension); //获取图片访问地址 String url=IMAGE_DOMAIN+upload[0]+"/"+upload[1]; return new Result(true,url); } }