1. 程式人生 > >JAVA簡單上傳圖片至七牛

JAVA簡單上傳圖片至七牛


utils


package com.example.demo.utils;

import com.alibaba.fastjson.JSONObject;
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.util.Auth;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @Author:lgl
 * @Description:
 * @Date:Create in 2018/3/9 .
 */
public class UploadImages {
    private static final Logger LOG = LogManager.getLogger("UploadArticle");

    public static final String ak = "***";
    public static final String sk = "***";
    public static final String bucket = "images"; //正式環境
    static Auth auth = Auth.create(ak, sk);

    /* 上傳至 華東 */
    static Zone z = Zone.zone0();
    static Configuration c = new Configuration(z);
    // 建立上傳物件
    static UploadManager uploadManager = new UploadManager(c);

    private static String QINIU_IMAGE_DOMAIN= "***";

    public static String getUpToken() {
        return auth.uploadToken(bucket);
    }

    public static String saveImage(MultipartFile file)throws IOException {
        String pic_type = file.getContentType();
        if (pic_type.equals("image/jpeg") || pic_type.equals("image/png") || pic_type.equals("image/bmp")
                || pic_type.equals("image/gif")) {
            try {
                String fileEnd = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                String fileName = UUID.randomUUID().toString().replaceAll("-", "") + fileEnd;
                //呼叫put方法上傳
                Response res = uploadManager.put(file.getBytes(), fileName, getUpToken());
                //列印返回的資訊
                if (res.isOK() && res.isJson()) {
                    return QINIU_IMAGE_DOMAIN + JSONObject.parseObject(res.bodyString()).get("key");
                } else {
                    LOG.error("七牛異常1:" + res.bodyString());
                    return null;
                }
            } catch (QiniuException e) {
                // 請求失敗時列印的異常的資訊
                Response r = e.response;
                System.out.println(r.toString());
                LOG.error("七牛異常2:" + e.getMessage());
                return null;
            }
        }else{
            return "非圖片";
        }
        }
}


jar


<dependency>
            <groupId>com.qiniu</groupId>
            <artifactId>qiniu-java-sdk</artifactId>
            <version>[7.2.0, 7.2.99]</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.17</version>
        </dependency>