集成七牛雲儲存-上傳圖片Demo


下面直接上方法,前段用文件流的形式,只需name的名稱與方法中的file相同即可。

*准備工作:
1、注冊一個七牛賬號,注冊鏈接:點擊注冊 ,注冊成功之后最好實名認證一下,每個月的流量以及空間的容量會增加很多。
2、新建一個空間,記下空間名稱(bucketName)。在賬號里找到密鑰:AK,SK。后面開發中會用到這些。
3、下載七牛jar文件,文章最后面有下載鏈接。

html代碼:

<input type="file" name="imgFile" />
/** * 圖片上傳工具類 * @author jcong * */
public class UploadingImageUtils {

    private static UploadManager uploadManager = new UploadManager();

    /** * * @param imgFile 圖片流 * @param imgName 圖片名稱 * @param bucketName 七牛空間名稱 * @param AK,SK 七牛密鑰 */
    public static String uploadingImage(MultipartFile imgFile,String imgName){
        Auth auth = Auth.create(AK,SK);
        String token = auth.uploadToken(bucketName);

        CommonsMultipartFile cf = (CommonsMultipartFile)imgFile;
        DiskFileItem fi = (DiskFileItem) cf.getFileItem();
        InputStream  inputStream = new FileInputStream(f);
        byte[] byteData = IOUtils.toByteArray(inputStream);
        Response response = uploadManager.put(byteData,imgName, token);
        response.bodyString();
    }
}

/**
 * 對上傳的圖片大小進行判斷
 * @param imgFile 圖片流
 */

public static boolean papers(MultipartFile imgFile){
     if(imgFile=null){
         System.out.println("上傳圖片大小是:"+imgFile1.getSize());
         if(imgFile1.getSize()<512000){
         List<String> fileTypes = new ArrayList<String>();  
            fileTypes.add("jpg");  
            fileTypes.add("jpeg");  
            fileTypes.add("png"); 
            String fileName = imgFile1.getOriginalFilename();
            //獲取上傳文件類型的擴展名,先得到.的位置,再截取從.的下一個位置到文件的最后,最后得到擴展名  
             String ext = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());  
             //對擴展名進行小寫轉換  
             ext = ext.toLowerCase();  
            if(fileTypes.contains(ext)) { //如果擴展名屬於允許上傳的類型,則創建文件  
                return true;
             }else{
                return false;
             }
         }else{
             return false;
         }
     }else{
         return false;
     }

}

控制層代碼:

/** * 上傳接口 * @param demo 實體類 */
@RequestMapping(value="/demo",method=RequestMethod.POST)
public ModelAndView Demo(MultipartHttpServletRequest req,Demo demo){
        ModelAndView mav=new ModelAndView();
        //首先判斷圖片是否符合上傳的要求(調用上面2-方法)
        if(UploadImageVerify.papers(req.getFile("imgFile"))){
            System.out.println("成功!");  

            //調用圖片上傳工具類
            String path=UploadingImageUtils.uploadingImage(demo.imgId(),req.getFile("imgFile"));
            //打印上傳的圖片路徑
            System.out.println("圖片路徑是:"+path);
            demo.setImg(path);
        }
        //將得到的圖片路徑寫入數據庫中
        jcDao.Demo(demo);
        mav.setViewName("forward:/WEB-INF/salesman/jcong.jsp");
        return mav;
    }

以上即是上傳圖片全部代碼。


在開發過程中,找到一個寫的比較完整的類,上面沒怎么看懂的朋友可以再參考一下下面的代碼內容,轉自:IT答案網

package com.yida.framework.base.util.qiniu;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.io.IOUtils;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.storage.model.FileListing;
import com.qiniu.util.Auth;

/** * @ClassName: QiniuUtils * @Description: 七牛操作工具類 * @author Lanxiaowei(736031305@qq.com) * @date 2015年12月8日 上午10:56:32 * */
public class QiniuUtils {
private static final String ACCESS_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
private static final String SECRET_KEY = "*******************************";
/**默認上傳空間*/
private static final String BUCKET_NAME = "XXXXXXXXXXXXXXX";
/**空間默認域名*/
private static final String BUCKET_HOST_NAME = "http://xxxxxxxxxxxxxxxx.clouddn.com";

private static UploadManager uploadManager = new UploadManager();

private static int LIMIT_SIZE = 1000;
/** * @Author: Lanxiaowei(736031305@qq.com) * @Title: listBucket * @Description: 返回七牛帳號的所有空間 * @param @return * @param @throws QiniuException * @return String[] * @throws */
public static String[] listBucket() throws QiniuException {
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
BucketManager bucketManager = new BucketManager(auth);
return bucketManager.buckets();
}

/** * @Author: Lanxiaowei(736031305@qq.com) * @Title: listFileOfBucket * @Description: 獲取指定空間下的文件列表 * @param bucketName 空間名稱 * @param prefix 文件名前綴 * @param limit 每次迭代的長度限制,最大1000,推薦值 100[即一個批次從七牛拉多少條] * @param @return * @return List<FileInfo> * @throws */
public static List<FileInfo> listFileOfBucket(String bucketName,String prefix,int limit) {
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
BucketManager bucketManager = new BucketManager(auth);
BucketManager.FileListIterator it = bucketManager.createFileListIterator(bucketName, prefix, limit, null);
List<FileInfo> list = new ArrayList<FileInfo>();
while (it.hasNext()) {
    FileInfo[] items = it.next();
    if (null != items && items.length > 0) {
        list.addAll(Arrays.asList(items));
    }
}
return list;
}


----------


/** * @Author: Lanxiaowei(736031305@qq.com) * @Title: uploadFile * @Description: 七牛圖片上傳 * @param @param inputStream 待上傳文件輸入流 * @param @param bucketName 空間名稱 * @param @param key 空間內文件的key * @param @param mimeType 文件的MIME類型,可選參數,不傳入會自動判斷 * @param @return * @param @throws IOException * @return String * @throws */
public static String uploadFile(InputStream inputStream,String bucketName,String key,String mimeType) throws IOException {  
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    String token = auth.uploadToken(bucketName);
    byte[] byteData = IOUtils.toByteArray(inputStream);
    Response response = uploadManager.put(byteData, key, token, null, mimeType, false);
    inputStream.close();
    return response.bodyString();
}


----------


/** * @Author: Lanxiaowei(736031305@qq.com) * @Title: uploadFile * @Description: 七牛圖片上傳 * @param @param inputStream 待上傳文件輸入流 * @param @param bucketName 空間名稱 * @param @param key 空間內文件的key * @param @return * @param @throws IOException * @return String * @throws */
public static String uploadFile(InputStream inputStream,String bucketName,String key) throws IOException {  
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    String token = auth.uploadToken(bucketName);
    byte[] byteData = IOUtils.toByteArray(inputStream);
    Response response = uploadManager.put(byteData, key, token, null, null, false);
    inputStream.close();
    return response.bodyString();
}


----------


/** * @Author: Lanxiaowei(736031305@qq.com) * @Title: uploadFile * @Description: 七牛圖片上傳 * @param filePath 待上傳文件的硬盤路徑 * @param fileName 待上傳文件的文件名 * @param bucketName 空間名稱 * @param key 空間內文件的key * @param @return * @param @throws IOException * @return String * @throws */
public static String uploadFile(String filePath,String fileName,String bucketName,String key) throws IOException {  
    Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    String token = auth.uploadToken(bucketName);
    InputStream is = new FileInputStream(new File(filePath + fileName));
    byte[] byteData = IOUtils.toByteArray(is);
    Response response = uploadManager.put(byteData, (key == null || "".equals(key))? fileName : key, token);
    is.close();
    return response.bodyString();
}


----------


/** * @Author: Lanxiaowei(736031305@qq.com) * @Title: uploadFile * @Description: 七牛圖片上傳[若沒有指定文件的key,則默認將fileName參數作為文件的key] * @param filePath 待上傳文件的硬盤路徑 * @param fileName 待上傳文件的文件名 * @param bucketName 空間名稱 * @param @return * @param @throws IOException * @return String * @throws */
public static String uploadFile(String filePath,String fileName,String bucketName) throws IOException {  
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    String token = auth.uploadToken(bucketName);
    InputStream is = new FileInputStream(new File(filePath + fileName));
    byte[] byteData = IOUtils.toByteArray(is);
    Response response = uploadManager.put(byteData, fileName, token);
    is.close();
    return response.bodyString();
}


----------


/** * @throws QiniuException * @Author: Lanxiaowei(736031305@qq.com) * @Title: fetchToBucket * @Description: 提取網絡資源並上傳到七牛空間里 * @param url 網絡上一個資源文件的URL * @param bucketName 空間名稱 * @param key 空間內文件的key[唯一的] * @param @return * @return String * @throws */
public static String fetchToBucket(String url,String bucketName,String key) throws QiniuException {
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
BucketManager bucketManager = new BucketManager(auth);
DefaultPutRet putret = bucketManager.fetch(url, bucketName, key);
return putret.key;
}


----------


/** * @Author: Lanxiaowei(736031305@qq.com) * @Title: fetchToBucket * @Description: 提取網絡資源並上傳到七牛空間里,不指定key,則默認使用url作為文件的key * @param url * @param bucketName * @param @return * @param @throws QiniuException * @return String * @throws */
public static String fetchToBucket(String url,String bucketName) throws QiniuException {
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
BucketManager bucketManager = new BucketManager(auth);
DefaultPutRet putret = bucketManager.fetch(url, bucketName);
return putret.key;
}


----------


/** * @throws QiniuException * @Author: Lanxiaowei(736031305@qq.com) * @Title: copyFile * @Description: 七牛空間內文件復制 * @param bucket 源空間名稱 * @param key 源空間里文件的key(唯一的) * @param targetBucket 目標空間 * @param targetKey 目標空間里文件的key(唯一的) * @return void * @throws */
public static void copyFile(String bucket, String key, String targetBucket, String targetKey) throws QiniuException {
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
BucketManager bucketManager = new BucketManager(auth);
bucketManager.copy(bucket, key, targetBucket, targetKey);
}


----------


/** * @Author: Lanxiaowei(736031305@qq.com) * @Title: moveFile * @Description: 七牛空間內文件剪切 * @param bucket 源空間名稱 * @param key 源空間里文件的key(唯一的) * @param targetBucket 目標空間 * @param targetKey 目標空間里文件的key(唯一的) * @param @throws QiniuException * @return void * @throws */
public static void moveFile(String bucket, String key, String targetBucket, String targetKey) throws QiniuException {
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
BucketManager bucketManager = new BucketManager(auth);
bucketManager.move(bucket, key, targetBucket, targetKey);
}


----------


/** * @Author: Lanxiaowei(736031305@qq.com) * @Title: renameFile * @Description: 七牛空間內文件重命名 * @param bucket * @param key * @param targetKey * @param @throws QiniuException * @return void * @throws */
public static void renameFile(String bucket, String key, String targetKey) throws QiniuException {
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
BucketManager bucketManager = new BucketManager(auth);
bucketManager.rename(bucket, key, targetKey);
}


----------


/** * @Author: Lanxiaowei(736031305@qq.com) * @Title: deleteFile * @Description: 七牛空間內文件刪除 * @param bucket 空間名稱 * @param key 空間內文件的key[唯一的] * @param @throws QiniuException * @return void * @throws */
public static void deleteFile(String bucket, String key) throws QiniuException {
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
BucketManager bucketManager = new BucketManager(auth);
bucketManager.delete(bucket, key);
}


----------


/** * @Author: Lanxiaowei(736031305@qq.com) * @Title: findFiles * @Description: 返回指定空間下的所有文件信息 * @param @param bucketName 空間名稱 * @param @param prefix 文件key的前綴 * @param @param limit 批量提取的最大數目 * @param @return * @param @throws QiniuException * @return FileInfo[] * @throws */
public static FileInfo[] findFiles(String bucketName,String prefix,int limit) throws QiniuException {
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
BucketManager bucketManager = new BucketManager(auth);
FileListing listing = bucketManager.listFiles(bucketName, prefix, null, limit, null);
if(listing == null || listing.items == null || listing.items.length <= 0) {
return null;
}
return listing.items;
}


----------


/** * @Author: Lanxiaowei(736031305@qq.com) * @Title: findFiles * @Description: 返回指定空間下的所有文件信息 * @param @param bucketName 空間名稱 * @param @param prefix 文件key的前綴 * @param @return * @param @throws QiniuException * @return FileInfo[] * @throws */
public static FileInfo[] findFiles(String bucketName,String prefix) throws QiniuException {
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
BucketManager bucketManager = new BucketManager(auth);
FileListing listing = bucketManager.listFiles(bucketName, prefix, null, LIMIT_SIZE, null);
if(listing == null || listing.items == null || listing.items.length <= 0) {
return null;
}
return listing.items;
}


----------


/** * @Author: Lanxiaowei(736031305@qq.com) * @Title: findFiles * @Description: 返回指定空間下的所有文件信息 * @param @param bucketName * @param @param key * @param @return * @param @throws QiniuException * @return FileInfo[] * @throws */
public static FileInfo[] findFiles(String bucketName) throws QiniuException {
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
BucketManager bucketManager = new BucketManager(auth);
FileListing listing = bucketManager.listFiles(bucketName, null, null, LIMIT_SIZE, null);
if(listing == null || listing.items == null || listing.items.length <= 0) {
return null;
}
return listing.items;
}


----------


/** * @Author: Lanxiaowei(736031305@qq.com) * @Title: findOneFile * @Description: 返回指定空間下的某個文件 * @param @param bucketName * @param @param key * @param @param limit * @param @return * @param @throws QiniuException * @return FileInfo * @throws */
public static FileInfo findOneFile(String bucketName,String key,int limit) throws QiniuException {
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
BucketManager bucketManager = new BucketManager(auth);
FileListing listing = bucketManager.listFiles(bucketName, key, null, limit, null);
if(listing == null || listing.items == null || listing.items.length <= 0) {
return null;
}
return (listing.items)[0];
}


----------


/** * @Author: Lanxiaowei(736031305@qq.com) * @Title: findOneFile * @Description: 返回指定空間下的某個文件(重載) * @param @param bucketName * @param @param key * @param @return * @param @throws QiniuException * @return FileInfo * @throws */
public static FileInfo findOneFile(String bucketName,String key) throws QiniuException {
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
BucketManager bucketManager = new BucketManager(auth);
FileListing listing = bucketManager.listFiles(bucketName, key, null, LIMIT_SIZE, null);
if(listing == null || listing.items == null || listing.items.length <= 0) {
return null;
}
return (listing.items)[0];
}


----------


       /** * @Author: Lanxiaowei(736031305@qq.com) * @Title: getFileAccessUrl * @Description: 返回七牛空間內指定文件的訪問URL * @param @param key * @param @return * @param @throws QiniuException * @return String * @throws */
public static String getFileAccessUrl(String key) throws QiniuException {
return BUCKET_HOST_NAME + "/" + key;
}

public static void main(String[] args) throws IOException {
//uploadFile("C:/test.jpg");

/*String[] buckets = listBucket(); for(String bucket : buckets) { System.out.println(bucket); }*/

/*List<FileInfo> list = listFileOfBucket(BUCKET_NAME, null, 1000); for(FileInfo fileInfo : list) { System.out.println("key:" + fileInfo.key); System.out.println("hash:" + fileInfo.hash); System.out.println("................"); }*/

//copyFile(BUCKET_NAME, "images-test", BUCKET_NAME, "images-test-1111");

//renameFile(BUCKET_NAME, "images-test-1111", "images-test-2222.jpg");

//deleteFile(BUCKET_NAME, "images-test-2222.jpg");

//fetchToBucket("http://www.nanrenwo.net/uploads/allimg/121026/14-1210261JJD03.jpg", BUCKET_NAME,"1111111111111111.jpg");

FileInfo[] fileInfos = findFiles(BUCKET_NAME, "10", LIMIT_SIZE);
for(FileInfo fileInfo : fileInfos) {
System.out.println(fileInfo.key);
System.out.println(fileInfo.hash);
System.out.println("..............");
}
}
}

最后,友情提醒:如果開發過程中遇到報錯實在無法理解的地方。可以嘗試一下更換架包文件,本人在開發過程中,用的是七牛官網下載的架包,可能是與本地的某java架包起沖突,導致上傳成功卻一直報錯,頭疼,最后找了一下版本低一點的七牛架包,問題解決。
用到的七牛架包文件:點擊下載
網盤密碼:ng83


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM