主要用的ssm框架,前端用的是angularjs,图片服务器用的是fastdfs.
1、加入依赖:
<dependencies>
<!-- 文件服务器 -->
<dependency>
<groupId>org.csource.fastdfs</groupId>
<artifactId>fastdfs</artifactId>
</dependency>
<!--文件上传组件-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
</dependency>
</dependencies>
2、文件上传封装的工具类:
package com.soft.utils;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
/**
* FastDFS工具类
*/
public class FastDFSClient {
private TrackerClient trackerClient = null;
private TrackerServer trackerServer = null;
private StorageServer storageServer = null;
private StorageClient1 storageClient = null;
/**
* 构造方法,加载配置文件,初始化对象
* @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);
}
}
3、在resources文件下添加fdfs_client.conf和application.properties配置文件:
fdfs_client.conf:
tracker_server=192.168.25.133:22122
application.properties(主要用于图片回显地址拼接):
tracker_server=192.168.25.133:22122
4、在springmvc的配置文件中配置上传解析器:
<!--配置文件上传解析器对象-->
<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>
5、angularjs前端异步上传代码(anjularjs对于post和get请求默认的Content-Type header 是application/json。
通过设置‘Content-Type’: undefined,这样浏览器会帮我们把Content-Type 设置为 multipart/form-data。通过设置 transformRequest: angular.identity ,anjularjs transformRequest function 将序列化我们的formdata。):
// 文件上传
$scope.uploadFile=function(){
// 存储表单数据
var formData=new FormData();
// 向表单中添加file属性和值
formData.append("file",file.files[0]);
// 文件上传
$http({
method:'POST',
url:"../upload",
data: formData,
headers: {'Content-Type':undefined},
transformRequest: angular.identity}).
then(function successCallback(resp) {
// 请求成功执行代码
if(resp.data.success){
$scope.image.url = resp.data.data;
}else{
alert(resp.data.message);
}
});
};
6、后台controller代码:
package cn.tx.controller;
import cn.tx.entity.Result;
import cn.tx.utils.FastDFSClient;
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;
@RestController
public class UploadController {
// 从application.properties配置文件中读取配置文件
@Value("${FILE_SERVER_URL}")
private String FILE_SERVER_URL;
/**
* 文件上传
* @param file
* @return
*/
@RequestMapping("/upload")
public Result upload(MultipartFile file) {
// 获取上传文件的名称
String originalFilename = file.getOriginalFilename();
// 获取上传文件的后缀名
String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
try {
// 创建一个 FastDFS 的客户端对象
FastDFSClient fastDFSClient = new FastDFSClient("classpath:config/fdfs_client.conf");
// 执行上传处理
String path = fastDFSClient.uploadFile(file.getBytes(), extName);
// 拼接返回的 url 和 ip 地址,拼装成完整的 url
String url = FILE_SERVER_URL + path;
return new Result(true, "上传成功",url);
} catch (Exception e) {
e.printStackTrace();
return new Result(false, "上传失败");
}
}
}