七牛云存储

七牛云存储

Scroll Down
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.common.Zone;
import com.qiniu.storage.Configuration;
import com.qiniu.util.Auth;

import java.io.IOException;


public class QiniuUpload {
    //设置好账号的ACCESS_KEY和SECRET_KEY
    public static String ACCESS_KEY = “xx”;
    public static String SECRET_KEY = “xx”;
    //要上传的空间
    public static String bucketname = “xx”;
    //上传到七牛后保存的文件名
    public static String key = “my-java.png”;
    //上传文件的路径
    public static String FilePath = “/…/…”;
    //密钥配置
    public static Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    public static Zone z = Zone.autoZone();
    public static  Configuration c = new Configuration(z);
    //创建上传对象
    public static UploadManager uploadManager = new UploadManager(c);

    //简单上传,使用默认策略,只需要设置上传的空间名就可以了
    public static  String getUpToken() {
        return auth.uploadToken(bucketname);
    }

    public static synchronized void upload() throws IOException {
        try {
            //调用put方法上传
            Response res = uploadManager.put(FilePath, key, getUpToken());
            //打印返回的信息
            System.out.println(res.bodyString());
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            System.out.println(r.toString());
            try {
                //响应的文本信息
                System.out.println(r.bodyString());
            } catch (QiniuException e1) {
            }
        }
    }

}
		<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>

在结合SpringMvc的时候可以先将文件上传到服务器,接着讲文件从服务器上传到七牛,然后将文件在七牛的地址返回给前台。