1. 程式人生 > >圖片上傳功能(FastDFS圖片伺服器 kindEditor富文字編輯器)

圖片上傳功能(FastDFS圖片伺服器 kindEditor富文字編輯器)

第一步 : 新增jar包

                    Commons-io、fileupload,兩個jar包

第二步:在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>

第三步: 因為 kindEditor富文字編輯器上傳的特性要為結果集建立一個封裝類

public class PictureResult {

	private int error;
	private String url;
	private String message;
	public int getError() {
		return error;
	}
	public void setError(int error) {
		this.error = error;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	
}

第三步:接收圖片資料,把圖片上傳到圖片伺服器,返回PictureResult 。需要使用FastDFSClient工具類。

1、FastDFSClient工具類

package com.yunhe.common.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;

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:")) {
	    	System.out.println("before conf======"+conf);
	        conf = conf.replace("classpath:", this.getClass().getResource("/").getPath());
	        System.out.println("after conf======"+conf);
	    }
	    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、圖片上傳工具類

package com.yunhe.common.utils;

import org.springframework.web.multipart.MultipartFile;

import com.yunhe.common.pojo.PictureResult;


public class PictureUtil {
	
	public static PictureResult uploadFile(MultipartFile uploadFile,String img_addr){
		PictureResult res = new PictureResult();
		if(uploadFile != null){
			try {
				FastDFSClient fdfsClient = new FastDFSClient("classpath:client.conf");
				String originalFilename = uploadFile.getOriginalFilename();
				String ext = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
				String url = fdfsClient.uploadFile(uploadFile.getBytes(),ext);
				url = img_addr +url;
				System.out.println(url);
				res.setError(0);
				res.setUrl(url);
			} catch (Exception e) {
				res.setError(1);
				res.setMessage("圖片上傳失敗!");
				e.printStackTrace();
			}
		}else{
			res.setError(1);
			res.setMessage("圖片為空!");
		}
		return res;
	}

}

 

3.在controller實現圖片上傳

package com.yunhe.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.yunhe.common.pojo.PictureResult;
import com.yunhe.common.utils.JsonUtils;
import com.yunhe.common.utils.PictureUtil;
/**
 * 圖片相容性問題
 * 不能直接返回物件 然後註解方式返回json  因為其他瀏覽器不識別請求頭
 * 應該返回json字串
 * @author Administrator
 */
@Controller
public class pictureUploadContorller {
	
	@Value("${IMG_URL}")
	private String img_url;
	
	
	@RequestMapping(value="/pic/upload",produces=MediaType.TEXT_PLAIN_VALUE+";charset=utf-8")//Content-Type: text/plain;charset=UTF-8
	@ResponseBody
	public String uploadFile(MultipartFile uploadFile){
		 PictureResult pictureResult = PictureUtil.uploadFile(uploadFile, img_url);
		 String json = JsonUtils.objectToJson(pictureResult);
		return json;
	}
}

 

4.​​​​​​、載入屬性檔案

(1)建立一個屬性檔案.        (2)使用spring容器掃描屬性檔案。   (3)@Value註解取屬性的值

 

5、解決瀏覽器相容性問題

要求返回的資料是一個文字型別,要求content-type 為text/plan