七牛云demo,文件上传demo

本文提供了一个使用七牛云存储服务进行文件上传的Java示例代码,展示了如何通过七牛云SDK获取上传凭证、配置上传管理器并完成文件上传的过程。同时,还给出了一个简单的文件下载链接生成示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.tc.art.qiniuyun;

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;

/**
 * @author 七牛云上传
 */
public class UploadDemo {


    public static void main(String[] args) {
        String accessKey = "xxxx";
        String secretKey = "xxxx";
        String bucket = "bucket2";
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        System.out.println(upToken);

        Configuration cfg = new Configuration(Zone.zone0());


        UploadManager uploadManager = new UploadManager(cfg);
        String key = null;
        String localFilePath = "C:\\Users\\Administrator\\Downloads\\DiskCalculator.rar";

        try {
            Response response = uploadManager.put(localFilePath, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
                ex2.printStackTrace();
                Response response = ex2.response;
                System.out.println(response.toString());
            }
        }
    }
}
 

 

package com.tc.art.qiniuyun;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class DownDemo {


    public static void main(String[] args) throws UnsupportedEncodingException {
        String fileName = "FjtsHlJCf4LJwU5oljNQPiYmkLbB";
        String domainOfBucket = "http://xxxxx";
        String encodedFileName = URLEncoder.encode(fileName, "utf-8");
//        String publicUrl = String.format("%s/%s", domainOfBucket, encodedFileName);
//        String accessKey = "SCerPf6t304mqDi-U8UQASDqYz5jgUxf4SU8HWCt";
//        String secretKey = "VFm0c_4QMQQOpup-jtkcU9dN57IqOOxr0jASnlfV";
//

        String finalUrl = String.format("%s/%s", domainOfBucket, encodedFileName);
        System.out.println(finalUrl);

//预览  domainOfBucket+finalUrl

    }
}
 

注意webserver(tomcat、nginx)的默认文件上传限制。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值