图片上传功能(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

猜你喜欢

转载自blog.csdn.net/hsw201508130017/article/details/85006052