FastDFS java客户端文件上传demo

FastDFS不多讲,直接上java调用代码,以下代码是一个spring mvc中一个完整的上传请求,请参阅

 

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	@ResponseBody
	public Object upload(@RequestParam MultipartFile file) {
		UploadResponse res = new UploadResponse();
		try {
			if(file.isEmpty()){
				res.setRet_code(UserCodeEnum.ERR_FILE_NULL.getCode());
				res.setRet_msg(UserCodeEnum.ERR_FILE_NULL.getDesc());
			}else{
				logger.info("UserController-upload-request-file=" + file.getOriginalFilename());
				
				String tempFileName = file.getOriginalFilename();
				//fastDFS方式
				ClassPathResource cpr = new ClassPathResource("fdfs_client.conf");
				ClientGlobal.init(cpr.getClassLoader().getResource("fdfs_client.conf").getPath());
				byte[] fileBuff = file.getBytes();
			    String fileId = "";
			    String fileExtName = tempFileName.substring(tempFileName.lastIndexOf("."));
				
			    //建立连接
			    TrackerClient tracker = new TrackerClient();
			    TrackerServer trackerServer = tracker.getConnection();
			    StorageServer storageServer = null;
			    StorageClient1 client = new StorageClient1(trackerServer, storageServer);
			    
			    //设置元信息
			    NameValuePair[] metaList = new NameValuePair[3];
			    metaList[0] = new NameValuePair("fileName", tempFileName);
			    metaList[1] = new NameValuePair("fileExtName", fileExtName);
			    metaList[2] = new NameValuePair("fileLength", String.valueOf(file.getSize()));
			    
			    //上传文件
			    fileId = client.upload_file1(fileBuff, fileExtName, metaList);
			    
			    res.setHead_img(UserConstants.FILE_IMG_URL+fileId);
			    
				res.setRet_code(UserCodeEnum.SUCCESS.getCode());
				res.setRet_msg(UserCodeEnum.SUCCESS.getDesc());
			}
			
			logger.info("UserController-upload-response-" + JsonUtils.o2j(res));
		} catch (Exception e) {
			res.setRet_code(UserCodeEnum.ERR_UNKNOWN.getCode());
			res.setRet_msg(UserCodeEnum.ERR_UNKNOWN.getDesc());
			logger.error("UserController-upload-error", e);
		}
		return res;
	}

 fileId是fastDFS返回的文件路径,fastDFS是可以使用自带的web服务访问文件,也可以集成第三方例如nginx。

 

 

fastDFS java客户端配置文件fdfs_client.conf配置如下:

connect_timeout = 30
network_timeout = 60
charset = ISO8859-1
http.tracker_http_port = 8090
http.anti_steal_token = no
http.secret_key = 123456

tracker_server = 192.168.11.***:22122

 

至此完成,通过网页简单测试即可,注意表单名称应与接口一直,命名为file

你可能感兴趣的:(fastDFS)