微信小程序 - 後臺接入七牛雲上傳圖片和視頻

在後臺上傳資源文件過程當中,通常都是上傳到本身的遠程 Linux 服務器上,若是本身不想搭建本身的靜態資服務器,咱們可使用七牛雲服務器,在這裏咱們不討論七牛雲的優劣,只分享討論它的使用方法便可。java

一、註冊本身的七牛帳號,而且實名認證以後,可使用它的對象存儲功能web

進入七牛官網 :www.qiniu.com  註冊本身的帳號spring

管理控制檯 --> 選擇對象存儲 --> 新建存儲空間 --> 填寫表單 --> 建立完成服務器

二、到本身的我的中心查看 AccessKey/SecretKey 並在後臺代碼配置這兩個參數app

三、使用七牛 java 的 sdk學習

查看下載地址:https://developer.qiniu.com/kodo/sdk/1239/javagoogle

<dependencies>
    <dependency>
      <groupId>com.qiniu</groupId>
      <artifactId>qiniu-java-sdk</artifactId>
      <version>7.2.11</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.squareup.okhttp3</groupId>
      <artifactId>okhttp</artifactId>
      <version>3.3.1</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.6.2</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.qiniu</groupId>
      <artifactId>happy-dns-java</artifactId>
      <version>0.1.4</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

四、完成以上步驟,那就直接上代碼.net

package com.thinkgem.jeesite.modules.zsgt.utils;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Paths;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.persistent.FileRecorder;
import com.qiniu.util.Auth;


/**
 * 七牛雲圖片上傳
 * 
 * @author hp
 */
public class QiniuUpload {

	/**
	 * 七牛雲圖片路徑
	 */
	public static final String QINIU_IMG_PATH = "xxx";

	// ...生成上傳憑證,而後準備上傳
	private static String accessKey = "xxx";
	private static String secretKey = "xxx";
	private static String bucket = "xxx";

	// 構造一個帶指定Zone對象的配置類
	private static Configuration cfg = new Configuration(Zone.zone2());

	// 上傳文件到七牛雲
	public String upload(File file) {
		String fileName = "";
		UploadManager uploadManager = new UploadManager(cfg);
		// 默認不指定key的狀況下,以文件內容的hash值做爲文件名
		String key = new Date().getTime() + "_" + file.getName();
		Auth auth = Auth.create(accessKey, secretKey);
		String upToken = auth.uploadToken(bucket);
		try {
			Response response = uploadManager.put(file, key, upToken);
			// 解析上傳成功的結果
			DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
			fileName = putRet.key;
		} catch (QiniuException ex) {
			Response r = ex.response;
			System.err.println(r.toString());
			try {
				System.err.println(r.bodyString());
			} catch (QiniuException ex2) {
				// ignore
			}
		}
		return fileName;
	}

	// 刪除文件
	public boolean delete(String hasName) {
		boolean deleteType = false;
		Auth auth = Auth.create(accessKey, secretKey);
		BucketManager bucketManager = new BucketManager(auth, cfg);
		try {
			bucketManager.delete(bucket, hasName);
			deleteType = true;
		} catch (QiniuException ex) {
			// 若是遇到異常,說明刪除失敗
			System.err.println(ex.code());
			System.err.println(ex.response.toString());
		}
		return deleteType;
	}

	public static String uploadBlock(File file) {
		String fileName = "";
		// 默認不指定key的狀況下,以文件內容的hash值做爲文件名
		String key = new Date().getTime() + "_" + file.getName();

		Auth auth = Auth.create(accessKey, secretKey);
		String upToken = auth.uploadToken(bucket);

		String localTempDir = Paths.get(System.getenv("java.io.tmpdir"), bucket).toString();
		try {
			// 設置斷點續傳文件進度保存目錄
			FileRecorder fileRecorder = new FileRecorder(localTempDir);
			UploadManager uploadManager = new UploadManager(cfg, fileRecorder);
			try {
				Response response = uploadManager.put(file, key, upToken);
				// 解析上傳成功的結果
				DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
				fileName = putRet.key;
			} catch (QiniuException ex) {
				Response r = ex.response;
				System.err.println(r.toString());
				try {
					System.err.println(r.bodyString());
				} catch (QiniuException ex2) {
					// ignore
				}
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return fileName;
	}
	
	public static String upload(HttpServletRequest request, MultipartFile img){
		String path = request.getSession().getServletContext().getRealPath("/file/upload/");// 生成一個目錄
		File file;
		try {
			file = FileUtil.getFile(path, img);
		} catch (Exception e) {
			throw new RuntimeException("上傳文件失敗");
		}
		String fileName = QiniuUpload.uploadBlock(file);
		return QiniuUpload.QINIU_IMG_PATH + URLEncoder.encode(fileName);// 訪問路徑
	}

}

使用你的 AccessKey/SecretKey 而後調用 QiniuUpload.upload(request, Img) 便可實現上傳操做,更多上傳操做請看 java 七牛 sdk 文檔 ,使用七牛封裝好的方法會更加簡單。code

 

水平有限,如有問題請留言交流!xml

互相學習,共同進步 :) 轉載請註明出處謝謝!

相關文章
相關標籤/搜索