天天看点

使用fastDFS在angularjs中实现文件上传

如何使用fastDFS在angularjs中实现文件上传:

  1. 先在后端引入相关的jar包:
    <dependency>
     	<groupId>org.csource.fastdfs</groupId>
     	<artifactId>fastdfs</artifactId>
     	<version>1.2</version>
     </dependency>
     <!-- 文件上传组件 -->
     <dependency>
     	<groupId>commons-fileupload</groupId>
     	<artifactId>commons-fileupload</artifactId>
     	<version>1.3.1</version>
     </dependency>
               
  2. 配置工具类:
    public class FastDFSClient {
    
     	private TrackerClient trackerClient = null;
     	private TrackerServer trackerServer = null;
     	private StorageServer storageServer = null;
     	private StorageClient1 storageClient = null;
     	
     	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);
     	}
     }
               

2.1 读取配置文件:

application.properties配置文件内容:FILE_SERVER_URL=http://192.168.25.133/

fdfs_client.conf配置文件内容:

# connect timeout in seconds
# default value is 30s
connect_timeout=30

# network timeout in seconds
# default value is 30s
network_timeout=60

# the base path to store log files
base_path=/home/fastdfs

# tracker_server can ocur more than once, and tracker_server format is
#  "host:port", host can be hostname or ip address
tracker_server=192.168.25.133:22122

#standard log level as syslog, case insensitive, value list:
### emerg for emergency
### alert
### crit for critical
### error
### warn for warning
### notice
### info
### debug
log_level=info

# if use connection pool
# default value is false
# since V4.05
use_connection_pool = false

# connections whose the idle time exceeds this time will be closed
# unit: second
# default value is 3600
# since V4.05
connection_pool_max_idle_time = 3600

# if load FastDFS parameters from tracker server
# since V4.05
# default value is false
load_fdfs_parameters_from_tracker=false

# if use storage ID instead of IP address
# same as tracker.conf
# valid only when load_fdfs_parameters_from_tracker is false
# default value is false
# since V4.05
use_storage_id = false

# specify storage ids filename, can use relative or absolute path
# same as tracker.conf
# valid only when load_fdfs_parameters_from_tracker is false
# since V4.05
storage_ids_filename = storage_ids.conf


#HTTP settings
http.tracker_server_port=80

#use "#include" directive to include HTTP other settiongs
##include http.conf


           
  1. 后端Controller代码:
@RestController
@RequestMapping("/upload")
public class UploadFileController {
	
	//注解注入:读取properties文件,通过文件获取(url)(FILE_SERVER_URL=http://192.168.25.133/)
	@Value("${FILE_SERVER_URL}")
	private String fileServerUrl;
	
	@RequestMapping("/img")
	public Result img(MultipartFile file){
		//加载配置文件
		FastDFSClient client;
		try {
			client = new FastDFSClient("D:\\eclipse\\eclipse_Project\\pinyougou-parent\\pinyougou-shop-web\\src\\main\\resources\\config\\fdfs_client.conf");
			//获取上传文件的全名
			String originalFilename = file.getOriginalFilename();
			//切割文件全名,获取文件的后缀名(.jpg)
			String fileName = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
			//通过工具类的方法,以字节形式上传文件
			String uploadFile = client.uploadFile(file.getBytes(),fileName);
			//上传成功:返回文件的访问路径
			return new Result(true,fileServerUrl+uploadFile);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//上传失败:返回上传失败
			return new Result(false,"上传失败");
		}
		
	}

}
           
  1. 前端页面代码:
<td>
	<input type="file" id="file" />
	<!-- 当用户选中图片,然后点击上传,会调用绑定的ng-click事件,然后把返回的图片访问连接 使用angular表达式给到下面img标签的src属性中,这样就可以展示用户上传的图片了 -->
		<button class="btn btn-primary" type="button" ng-click="uploadFile()">
			上传
		</button>
</td>

<td>
	<img src="{{img_entity.url}}" width="200px" height="200px">
</td>
           
  1. 前端service.js代码 :
//服务层
app.service("uploadService", function ($http) {

    //上传文件
    this.uploadFile = function () {
        var fomtdata = new FormData();
        //file.files 等于 document.getElementById("file").files[0];获取id为file的file上传文件框的内容,0为key
        fomtdata.append("file", file.files[0]);
        return $http({
            url: "../upload/img.do",
            method: "post",
            data: fomtdata,
            //设置请求头,等于把请求头设置为multipart/form-data
            headers: { "Content-Type": undefined },
            transformRequest: angular.identity //让文件以二进制传输(序列化);
        })
    }
})
           
  1. 前端controller.js代码:
//控制层 
app.controller('goodsController', function ($scope, uploadService) {

$scope.img_entity = { url: "", color: "" };//定义对象

//上传文件
	$scope.uploadFile = function () {
		uploadService.uploadFile().success(
			function (response) {
				if (response.flag) {
				//如果上传成功,把响应回来的文件访问链接赋值给$scope.img_entity.url 
					$scope.img_entity.url = response.msg;
				} else {
					alert("上传失败");
				}
			}
		)
	}

           

继续阅读