SpringMVC+AngualrJS实现文件上传到fastDFS服务器
后端
-
引入依赖
<!-- 文件上传组件 --> <dependency> <groupId>org.csource.fastdfs</groupId> <artifactId>fastdfs</artifactId> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> </dependency>
-
使用上传文件的工具类实现操作
/** * 文件上传 工具类 */ public class FastDFSClient { private TrackerClient trackerClient = null; private TrackerServer trackerServer = null; private StorageServer storageServer = null; private StorageClient1 storageClient = null; /** * 传入配置文件,获取文件上传需要的storageClient对象 * @param conf * @throws Exception */ public FastDFSClient(String conf) throws Exception { if (conf.contains("classpath:")) { conf = conf.replace("classpath:", this.getClass().getResource("/").getPath()); } ClientGlobal.init(conf); trackerClient = new TrackerClient(); trackerServer = trackerClient.getConnection(); storageServer = null; storageClient = new StorageClient1(trackerServer, storageServer); } /** * 上传文件方法 * <p>Title: uploadFile</p> * <p>Description: </p> * @param fileName 文件全路径 * @param extName 文件扩展名,不包含(.) * @param metas 文件扩展信息 * @return * @throws Exception */ public String uploadFile(String fileName, String extName, NameValuePair[] metas) throws Exception { String result = storageClient.upload_file1(fileName, extName, metas); return result; } public String uploadFile(String fileName) throws Exception { return uploadFile(fileName, null, null); } public String uploadFile(String fileName, String extName) throws Exception { return uploadFile(fileName, extName, null); } /** * 上传文件方法 * <p>Title: uploadFile</p> * <p>Description: </p> * @param fileContent 文件的内容,字节数组 * @param extName 文件扩展名 * @param metas 文件扩展信息 * @return * @throws Exception */ public String uploadFile(byte[] fileContent, String extName, NameValuePair[] metas) throws Exception { String result = storageClient.upload_file1(fileContent, extName, metas); return result; } public String uploadFile(byte[] fileContent) throws Exception { return uploadFile(fileContent, null, null); } public String uploadFile(byte[] fileContent, String extName) throws Exception { return uploadFile(fileContent, extName, null); } }
-
在sources下添加配置文件 application.properties : 存储请求图片的路径(http:10.207.130.187/)
FILE_SERVER_URL=http://10.207.130.187:9991/
-
添加fastDFS的配置文件: fdfs_client.conf ,配置“tracker_server”
tracker_server=10.207.130.187:22122
-
在springmvc的配置文件中配置
-
读取存储请求图片路径的配置文件
<!--读取配置文件的内容--> <context:property-placeholder location="classpath:config/application.properties" />
-
配置springmvc的多媒体解析器
<!-- 配置SpringMVC多媒体解析器,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="5242880"></property> </bean>
-
-
编写controller层
/** * 文件上传 控制类 */ @RestController public class UploadController { /** * 注入上传文件的服务器地址("http:10.207.130.187/") */ @Value("${FILE_SERVER_URL}") private String file_server_url; /** * 上传操作,传入“MultipartFile”对象 * @return */ @RequestMapping("/upload.do") public ResultInfo uploadFile(MultipartFile file){ //获取上传文件的后缀名 String originalFilename = file.getOriginalFilename(); //获取文件的全名(包括后缀名) String txName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1); //获取后缀名,不要"." try { //工具类加载配置文件fdfs_client.conf,获取FastDFSClient上传客户端 FastDFSClient fastDFSClient = new FastDFSClient("classpath:config/fdfs_client.conf"); //上传成功,后返回的file_id(从组名开始) String path = fastDFSClient.uploadFile(file.getBytes(), txName); //回显信息(请求图片的完整路径)到页面 return new ResultInfo(true,file_server_url + path); } catch (Exception e) { return new ResultInfo(false,"上传失败,请重新上传"); } } }
前端
上传与回显图片,使用angularJS
-
编写service
//文件上传的前端service app.service('uploadService',function ($http) { this.uploadFile = function () { //创建FormData对象,H5特有的文件上传对象 var formData = new FormData(); formData.append("file",file.files[0]);//(file:页面文件上传框的name) return $http({ method:'post', url:'../upload.do', data:formData, headers: {'Content-Type':undefined}, transformRequest: angular.identity }); } });
-
在controller中引入uploadService,定义方法
//图片上传 $scope.uploadFile = function () { uploadService.uploadFile().success(function (response) { if(response.flag){ //上传成功 $scope.image_entity.url =response.message; //获取图片上传后的url }else{ alert(response.message); //上传失败 } }) }
-
页面端。
需要额外引入uploadService.js文件
<script type="text/javascript" src="../js/service/uploadService.js"></script>
-
在表单中绑定 ng-modul,ng-click.显示图片的src则设置为controller中获取的url。点击“上传”调用controller中的方法
<table> <tr> <td> <input type="file" id="file" /> <button class="btn btn-primary" type="button" ng-click="uploadFile()" > 上传 </button> </td> <td> <img src="{{image_entity.url}}" width="200px" height="200px"> </td> </tr> </table>