1. 程式人生 > >商品圖片上傳(使用FastDFS)

商品圖片上傳(使用FastDFS)

在商品錄入介面實現多圖片上傳


當用戶點選新建按鈕,彈出上傳視窗

工程pom.xml引入依賴

<!-- 檔案上傳元件 -->

<dependency>

<groupId>org.csource.fastdfs</groupId>

<artifactId>fastdfs</artifactId>

</dependency>

<dependency>

<groupId>commons-fileupload</groupId>

<artifactId>commons-fileupload

</artifactId>

</dependency>

新建fastdfs工具類

         // 1、載入配置檔案,配置檔案中的內容就是 tracker 服務的地址。
		ClientGlobal.init("D:/maven_work/fastDFS-demo/src/fdfs_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:/pic/benchi.jpg", "jpg",
				null);
		// 7、返回陣列。包含組名和圖片的路徑。
		for (String string : strings) {
			System.out.println(string);
		}

(1)將“資源/fastDFS/配置檔案”資料夾中的fdfs_client.conf 拷貝到pinyougou-shop-web工程config資料夾

(2)在pinyougou-shop-web工程application.properties新增配置

FILE_SERVER_URL=http://192.168.25.133/

(3)在pinyougou-shop-web工程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>

控制層

在pinyougou-shop-web新建UploadController.java

package com.pinyougou.shop.controller;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import org.springframework.web.multipart.MultipartFile;

import entity.Result;

import util.FastDFSClient;

/**

 * 檔案上傳Controller

 * @author Administrator

 *

 */

@RestController

publicclass UploadController {

@Value("${FILE_SERVER_URL}")

private String FILE_SERVER_URL;//檔案伺服器地址

@RequestMapping("/upload")

public Result upload( MultipartFile file){             

//1、取檔案的副檔名

         String originalFilename = file.getOriginalFilename();

         String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

try {

//2、建立一個 FastDFS 的客戶端

             FastDFSClient fastDFSClient

= new FastDFSClient("classpath:config/fdfs_client.conf");

//3、執行上傳處理

             String path = fastDFSClient.uploadFile(file.getBytes(), extName);

//4、拼接返回的 urlip 地址,拼裝成完整的 url

             String url = FILE_SERVER_URL + path;          

returnnew Result(true,url);          

         } catch (Exception e) {

e.printStackTrace();

returnnew Result(false, "上傳失敗");

         }       

    }  

}