FastDFS图片服务器java后台的简单调用

工具类:

 1 package com.liveyc.common.fdfs;
 2 
 3 
 4 import org.apache.commons.io.FilenameUtils;
 5 import org.csource.common.NameValuePair;
 6 import org.csource.fastdfs.ClientGlobal;
 7 import org.csource.fastdfs.StorageClient1;
 8 import org.csource.fastdfs.StorageServer;
 9 import org.csource.fastdfs.TrackerClient;
10 import org.csource.fastdfs.TrackerServer;
11 import org.springframework.core.io.ClassPathResource;
12 
13 /**
14  * 上传图片到Fast
15  * @author lx
16  *
17  */
18 public class FastDFSUtils {
19     
20     /**
21      * @Description: 上传图片到Fast. 
22      * @Title: uploadPic   
23      * @author:  xuyou   
24      * @date:   2017年12月14日  
25      * @param pic 图片二进制
26      * @param name 图片名称
27      * @param size 图片大小
28      * @return
29      */
30     public static String uploadPic(byte[] pic ,String name,long size){
31         String path = null;
32         //ClientGloble 读配置文件
33         ClassPathResource resource = new ClassPathResource("fdfs_client.conf");
34         try {
35             ClientGlobal.init(resource.getClassLoader().getResource("fdfs_client.conf").getPath());
36             //老大客户端
37             TrackerClient trackerClient = new TrackerClient();
38             TrackerServer trackerServer = trackerClient.getConnection();
39             StorageServer storageServer  = null;
40             StorageClient1 storageClient1 = new StorageClient1(trackerServer, storageServer);
41             //图片11.jpg  根据图片名称得到图片后缀    jpg
42             String ext = FilenameUtils.getExtension(name);
43             
44             NameValuePair[] meta_list = new NameValuePair[3];
45             meta_list[0] = new NameValuePair("fileName",name);
46             meta_list[1] = new NameValuePair("fileExt",ext);
47             meta_list[2] = new NameValuePair("fileSize",String.valueOf(size));
48             
49             
50             //  group1/M00/00/01/wKjIgFWOYc6APpjAAAD-qk29i78248.jpg
51             path = storageClient1.upload_file1(pic, ext, meta_list);
52         } catch (Exception e) {
53             // TODO Auto-generated catch block
54             e.printStackTrace();
55         }
56         return path;
57     }
58 }

service层代码:

 1 package com.liveyc.core.service.product;
 2 
 3 
 4 
 5 import org.springframework.stereotype.Service;
 6 
 7 import com.liveyc.common.fdfs.FastDFSUtils;
 8 
 9 @Service("uploadService")
10 public class UploadServiceImpl implements UploadService{
11 
12     
13     //上传图片
14     public String uploadPic(byte[] pic ,String name,long size){
15         return FastDFSUtils.uploadPic(pic, name, size);
16     }
17 }

Controller层代码

1 //图片服务器
2 public static final String IMG_URL = "http://172.16.71.221/";
 1 package com.liveyc.core.controller;
 2 
 3 
 4 import java.io.IOException;
 5 import java.util.ArrayList;
 6 import java.util.List;
 7 import java.util.Map;
 8 import java.util.Map.Entry;
 9 import java.util.Set;
10 
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13 
14 import org.json.JSONObject;
15 import org.springframework.beans.factory.annotation.Autowired;
16 import org.springframework.stereotype.Controller;
17 import org.springframework.web.bind.annotation.RequestMapping;
18 import org.springframework.web.bind.annotation.RequestParam;
19 import org.springframework.web.bind.annotation.ResponseBody;
20 import org.springframework.web.multipart.MultipartFile;
21 import org.springframework.web.multipart.MultipartRequest;
22 
23 import com.liveyc.common.web.Constants;
24 import com.liveyc.core.service.product.UploadService;
25 
26 
27 /**
28  * 上传图片
29  * @author lx
30  *
31  */
32 @Controller
33 public class UploadController {
34 
35     @Autowired
36     private UploadService uploadService;
37     //上传图片  @RequestParam(required = false 防止为null 抛异常
38     @RequestMapping(value = "/upload/uploadPic.do")
39     public void uploadPic(@RequestParam(required = false) MultipartFile pic
40             ,HttpServletResponse response) throws IOException{
41         
42         String path = uploadService.uploadPic(pic.getBytes(), pic.getOriginalFilename(), pic.getSize());
43         
44         String url = Constants.IMG_URL + path;
45         
46         JSONObject  jo = new JSONObject();
47         jo.put("url", url);
48          
49         response.setContentType("application/json;charset=UTF-8");
50         response.getWriter().write(jo.toString());
51         
52     }
53     
54     //上传多张图片
55     @RequestMapping(value = "/upload/uploadPics.do")
56     public @ResponseBody
57     List<String> uploadPics(@RequestParam(required = false) MultipartFile[] pics
58             ,HttpServletResponse response) throws IOException{
59         
60         List<String> urls = new ArrayList<String>();
61         
62         for (MultipartFile pic : pics) {
63             String path = uploadService.uploadPic(pic.getBytes(), pic.getOriginalFilename(), pic.getSize());
64             String url = Constants.IMG_URL + path;
65             urls.add(url);
66         }
67         return urls;
68     }
69     
70 }

配置文件信息  将此文件放在service层所在项目中   其余不要动也就标红色的地方改下即可

 1 # connect timeout in seconds
 2 # default value is 30s
 3 connect_timeout=30
 4 
 5 # network timeout in seconds
 6 # default value is 30s
 7 network_timeout=60
 8 
 9 # the base path to store log files
10 base_path=/home/fastdfs
11 
12 # tracker_server can ocur more than once, and tracker_server format is
13 #  "host:port", host can be hostname or ip address
14 tracker_server=172.16.71.220:22122
15 #tracker_server=192.168.101.4:22122
16 
17 #standard log level as syslog, case insensitive, value list:
18 ### emerg for emergency
19 ### alert
20 ### crit for critical
21 ### error
22 ### warn for warning
23 ### notice
24 ### info
25 ### debug
26 log_level=info
27 
28 # if use connection pool
29 # default value is false
30 # since V4.05
31 use_connection_pool = false
32 
33 # connections whose the idle time exceeds this time will be closed
34 # unit: second
35 # default value is 3600
36 # since V4.05
37 connection_pool_max_idle_time = 3600
38 
39 # if load FastDFS parameters from tracker server
40 # since V4.05
41 # default value is false
42 load_fdfs_parameters_from_tracker=false
43 
44 # if use storage ID instead of IP address
45 # same as tracker.conf
46 # valid only when load_fdfs_parameters_from_tracker is false
47 # default value is false
48 # since V4.05
49 use_storage_id = false
50 
51 # specify storage ids filename, can use relative or absolute path
52 # same as tracker.conf
53 # valid only when load_fdfs_parameters_from_tracker is false
54 # since V4.05
55 storage_ids_filename = storage_ids.conf
56 
57 
58 #HTTP settings
59 http.tracker_server_port=80
60 
61 #use "#include" directive to include HTTP other settiongs
62 ##include http.conf

xml文件配置

service层

Controller层

jsp:

 js

 1 <script type="text/javascript">
 2 //上传图片
 3 function uploadPic(){
 4     //jquery.form.js
 5     var options = {
 6             url : "/upload/uploadPic.do",
 7             dataType : "json",
 8             type : "post",
 9             success : function(data){
10                 $("#allUrl").attr("src",data.url);
11                 $("#imgUrl").val(data.url);
12             }
13     }
14     $("#jvForm").ajaxSubmit(options);
15 }
16 </script>

测试结果:

 点击 选择图片以后 会立即把图片上传至fastdfs服务器  同时返回一条url连接

 

将连接 可在浏览器直接打开

原文地址:https://www.cnblogs.com/xuyou551/p/8037776.html