1. 程式人生 > >如何使用angularjs將圖片存到七牛雲上

如何使用angularjs將圖片存到七牛雲上

在頁面上:xxx.html

2.在 xxxcontroller.js層

 然後寫:

 

3.在uploadservice.js裡面

到了 後端:專門寫一個uplaodConctoller.java    就把圖片的地址傳到前端去了

這裡面 用到了寫的一個七牛雲的工具類:

package com.youmeishenghuo.convertion;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

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.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

public class PictureUtil {

	public static String accessKey = "這裡改成自己七牛雲的AS";
	public static String secretKey = "這裡改成自己七牛雲的S什麼的金鑰";
	public static String bucket = "這裡寫你在七牛雲建立的空間名字";

	private static String QINIU_IMAGE_DOMAIN = "http://pgtzuyqwd.bkt.clouddn.com/";//這裡也要改成你自己七牛雲裡的預設地址
            //傳入本地檔案地址
	public static String upload(String localFilePath) {
		// 構造一個帶指定Zone物件的配置類
		Configuration cfg = new Configuration(Zone.zone1());// 這裡是華北,對應1,華南,對應的2,你選擇的是華什麼就對應不同的數字
		UploadManager uploadManager = new UploadManager(cfg);
		// 預設不指定key的情況下,以檔案內容的hash值作為檔名
		String key = null;

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

		DefaultPutRet putRet = null;

		try {
			Response response = uploadManager.put(localFilePath, key, upToken);
			// 解析上傳成功的結果
			putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
		} catch (QiniuException ex) {
			Response r = ex.response;
			System.err.println(r.toString());
			try {
				System.err.println(r.bodyString());
			} catch (QiniuException ex2) {
				// ignore
			}
		}
		return QINIU_IMAGE_DOMAIN + putRet.hash;
	}
          //傳入一個流
	public static String upload(MultipartFile file) throws IOException {
		// 構造一個帶指定Zone物件的配置類
		Configuration cfg = new Configuration(Zone.zone1());
		UploadManager uploadManager = new UploadManager(cfg);
		// 預設不指定key的情況下,以檔案內容的hash值作為檔名
		String key = null;
		DefaultPutRet putRet = null;
		try {
			byte[] uploadBytes = file.getBytes();
			ByteArrayInputStream byteInputStream = new ByteArrayInputStream(uploadBytes);
			Auth auth = Auth.create(accessKey, secretKey);
			String upToken = auth.uploadToken(bucket);
			try {
				Response response = uploadManager.put(byteInputStream, key, upToken, null, null);
				putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
			} catch (QiniuException ex) {
				Response r = ex.response;
				System.err.println(r.toString());
				try {
					System.err.println(r.bodyString());
				} catch (QiniuException ex2) {
					// ignore
				}
			}
		} catch (UnsupportedEncodingException ex) {
			// ignore
		}
		return QINIU_IMAGE_DOMAIN + putRet.hash;
	}


}