34分布式电商项目 - 商品录入(图片上传至fastdfs)

上传图片至fastdfs
34分布式电商项目 - 商品录入(图片上传至fastdfs)_第1张图片

后端代码

1.pinyougou-common 工程 pom.xml 引入依赖

	
		
			commons-fileupload
			commons-fileupload
		
		
			org.csource.fastdfs
			fastdfs
		

2.编写工具类 FastDFSClient.java

package com.pyg.utils;
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);
	}
	
	/**
	 * 上传文件方法
	 * 

Title: uploadFile

*

Description:

* @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); } /** * 上传文件方法 *

Title: uploadFile

*

Description:

* @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); } }

3.把fdfs_client.conf文件拷贝到pinyougou-shop-web
工程 config 文件夹中。
34分布式电商项目 - 商品录入(图片上传至fastdfs)_第2张图片
4.在 pinyougou-shop-web 工程 application.properties 添加配置
34分布式电商项目 - 商品录入(图片上传至fastdfs)_第3张图片
5.在 pinyougou-shop-web 工程 springmvc.xml 添加配置:


	
		
		
	

6.在 pinyougou-shop-web 新建 UploadController.java

@RestController
@RequestMapping("/shop")
public class UploadController {
	
	
	//注入常量配置
	@Value("${IMAGE_SERVER_URL}")
	private String IMAGE_SERVER_URL;
	
	/**
	 * 需求:商家上传图片
	 * 请求:upload
	 * 参数:MultipartFile
	 * 返回值:PygResult
	 */
	@RequestMapping("/upload")
	public PygResult uploadPic(MultipartFile file){
		
		
		try {
			//获取文件名称
			String originalFilename = file.getOriginalFilename();
			//截取文件扩展名 
			String extName = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
			
			//创建工具类对象
			FastDFSClient fdfs = new FastDFSClient("classpath:config/client.conf");
			//上传文件
			//gif,bmp,jpg
			//返回文件上传成功地址:group1/M00/00/02/wKhCQ1qvKG2AZqibAA1rIuRd3Es806.jpg
			String url = fdfs.uploadFile(file.getBytes(), extName);
			
			//组合图片上传成功绝对地址
			url = IMAGE_SERVER_URL+url;
			
			//上传成功
			return new PygResult(true, url);
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//上传失败
			return new PygResult(false, "上传失败");
		}
		
		
	}

}

前端代码

1.在 pinyougou-shop-web 工程创建 uploadService.js

//文件上传服务层
app.service("uploadService",function($http){
	this.uploadFile=function(){
		var formData=new FormData();
		formData.append("file",file.files[0]); 
		return $http({
			 method:'POST',
			 url:"../upload.do",
			 data: formData,
			 headers: {'Content-Type':undefined},
			 transformRequest: angular.identity
		 });
	}
});

anjularjs 对于 post 和 get 请求默认的 Content-Type header 是 application/json。通过设置‘Content-Type’: undefined,这样浏览器会帮我们把 Content-Type 设置为 multipart/form-data.

通过设置 transformRequest: angular.identity ,anjularjs transformRequest function 将序列化我们的 formdata object.

2.将 uploadService 服务注入到 goodsController 中

//商品控制层(商家后台)
app.controller('goodsController' ,function($scope,$controller ,goodsService,itemCatService,uploadService){

3.在 goods_edit.html 引入 js







4.上传图片,goodsController 编写代码

/**
* 上传图片
*/
$scope.uploadFile=function(){ 
	uploadService.uploadFile().success(function(response) { 
		 if(response.success){//如果上传成功,取出 url
		 $scope.image_entity.url=response.message;//设置文件地址
	 }else{
		 alert(response.message);
	 }
	 }).error(function() {
		  alert("上传发生错误");
	  }); 
  };

5.修改图片上传窗口,调用上传方法,回显上传图片


你可能感兴趣的:(#,分布式电商)