項目中使用圖片服務器FastDFS

圖片服務器的搭建:

參考上一篇文章。

上傳步驟:

1、加載配置文件,配置文件中的內容就是tracker服務的地址。

配置文件內容:tracker_server=192.168.25.133:22122

2、創建一個TrackerClient對象。直接new一個。

3、使用TrackerClient對象創建連接,獲得一個TrackerServer對象。

4、創建一個StorageServer的引用,值爲null

5、創建一個StorageClient對象,需要兩個參數TrackerServer對象、StorageServer的引用

6、使用StorageClient對象上傳圖片。

7、返回數組。包含組名和圖片的路徑。

具體實現:

1.需要下載一個fastdfsClient項目1.25版本,導入項目,安裝到maven倉庫。

2.在manager-web項目的pom.xml中添加fastdfsClient的依賴。

3.在resources目錄下創建client.conf文件

tracker_server=192.168.25.133:22122

4.編寫一個測試類FastDFSTest 。

public class FastDFSTest {

	@Test
	public void testFileUpload() throws Exception {
		// 1、加載配置文件,配置文件中的內容就是tracker服務的地址。
		ClientGlobal.init("D:/workspaces-itcast/e3-manager-web/src/main/resources/resource/client.conf");
		// 2、創建一個TrackerClient對象。直接new一個。
		TrackerClient trackerClient = new TrackerClient();
		// 3、使用TrackerClient對象創建連接,獲得一個TrackerServer對象。
		TrackerServer trackerServer = trackerClient.getConnection();
		// 4、創建一個StorageServer的引用,值爲null
		StorageServer storageServer = null;
		// 5、創建一個StorageClient對象,需要兩個參數TrackerServer對象、StorageServer的引用
		StorageClient storageClient = new StorageClient(trackerServer, storageServer);
		// 6、使用StorageClient對象上傳圖片。
		//擴展名不帶“.”
		String[] strings = storageClient.upload_file("D:/Documents/Pictures/images/200811281555127886.jpg", "jpg", null);
		// 7、返回數組。包含組名和圖片的路徑。
		for (String string : strings) {
			System.out.println(string);
		}
	}
}

這裏提供一個工具類簡化代碼:

FastDFSClient.java

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;

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);
	}
}
使用工具類上傳:

@Test
	public void testFastDfsClient() throws Exception {
		FastDFSClient fastDFSClient = new FastDFSClient("D:/workspaces-itcast/e3-manager-web/src/main/resources/resource/client.conf");
		String file = fastDFSClient.uploadFile("D:/Documents/Pictures/images/2f2eb938943d.jpg");
		System.out.println(file);
	}

基於ssm框架的使用方法:

1.在manager-web項目中添加依賴

pom.xml

	<dependencies>
		<!-- 文件上傳組件 -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
		</dependency>
	</dependencies>
2.配置springmvc.xml

<!-- 定義文件上傳解析器 -->
	<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>
3.在resource目錄下創建conf目錄,添加client.conf文件

client.conf

tracker_server=192.168.25.133:22122

前端使用的是:KindEditor的多圖片上傳插件。

KindEditor 4.x 文檔http://kindeditor.net/doc.php

請求的url:/pic/upload

參數:MultiPartFile uploadFile

返回值:

//成功時
{
          "error" : 0,
          "url" : "http://www.xxxx.com/path/too/file.ext"
}
//失敗時
{
         "error" : 1,
         "message" : "錯誤信息"
}

4.controller編寫:

@Controller
public class PictureController {
	
	@Value("${IMAGE_SERVER_URL}")
	private String IMAGE_SERVER_URL;

	@RequestMapping("/pic/upload")
	@ResponseBody
	public Map fileUpload(MultipartFile uploadFile) {
		try {
			//1、取文件的擴展名
			String originalFilename = uploadFile.getOriginalFilename();
			String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
			//2、創建一個FastDFS的客戶端
			FastDFSClient fastDFSClient = new FastDFSClient("classpath:resource/client.conf");
			//3、執行上傳處理
			String path = fastDFSClient.uploadFile(uploadFile.getBytes(), extName);
			//4、拼接返回的url和ip地址,拼裝成完整的url
			String url = IMAGE_SERVER_URL + path;
			//5、返回map
			Map result = new HashMap<>();
			result.put("error", 0);
			result.put("url", url);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			//5、返回map
			Map result = new HashMap<>();
			result.put("error", 1);
			result.put("message", "圖片上傳失敗");
			return result;
		}
	}
}

這裏很可能出現遊覽器不兼容問題,需要把返回值對象轉換成json對象。

提供一個轉換工具類。

JsonUtils.java

import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 
 */
public class JsonUtils {

    // 定義jackson對象
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 將對象轉換成json字符串。
     * <p>Title: pojoToJson</p>
     * <p>Description: </p>
     * @param data
     * @return
     */
    public static String objectToJson(Object data) {
    	try {
			String string = MAPPER.writeValueAsString(data);
			return string;
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
    	return null;
    }
    
    /**
     * 將json結果集轉化爲對象
     * 
     * @param jsonData json數據
     * @param clazz 對象中的object類型
     * @return
     */
    public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
        try {
            T t = MAPPER.readValue(jsonData, beanType);
            return t;
        } catch (Exception e) {
        	e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 將json數據轉換成pojo對象list
     * <p>Title: jsonToList</p>
     * <p>Description: </p>
     * @param jsonData
     * @param beanType
     * @return
     */
    public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {
    	JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
    	try {
    		List<T> list = MAPPER.readValue(jsonData, javaType);
    		return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
    	return null;
    }
    
}
指定響應結果的content-type:




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章