<!-- 文件上传组件 -->
<dependency>
<groupId>org.csource.fastdfs</groupId>
<artifactId>fastdfs</artifactId>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
</dependency>
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 设定文件上传的最大值 5MB,5*1024*1024 -->
<property name="maxUploadSize" value="5242880"></property>
</bean>
package com.pinyougou.shop.controller;
import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile;
import entity.Result;
import util.FastDFSClient;
/**
*文件上传 Controller
*@author Administrator
*
*/ @RestController
public class UploadController {
@Value("${FILE_SERVER_URL}")
private String FILE_SERVER_URL;//文件服务器地址
@RequestMapping("/upload")
public Result upload( MultipartFile file){
//1、取文件的扩展名
String originalFilename = file.getOriginalFilename();
String extName = originalFilename.substring(originalFilename.lastIndexOf(".")
+ 1);
try {
//2、创建一个 FastDFS 的客户端
FastDFSClient fastDFSClient
= new FastDFSClient("classpath:config/fdfs_client.conf");
//3、执行上传处理
String path = fastDFSClient.uploadFile(file.getBytes(), extName);
//4、拼接返回的 url 和 ip 地址,拼装成完整的 url
String url = FILE_SERVER_URL + path;
return new Result(true,url);
} catch (Exception e) { e.printStackTrace();
return new Result(false, "上传失败");
}
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |