七牛云之上传demo

时间:2022-08-23 16:28:55
package com.zns.controller;

import com.google.gson.Gson;
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;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.FileInputStream;
import java.util.UUID;

@RequestMapping("/qiniu")
@Controller
public class QiNiuController {
    private String accessKey = "";
    private String secretKey = "";
    private String bucketName = "";
    private String fileDomain = "file.zns.com";
    private String fileDir = "/blog/article/thumbnail/";

    @RequestMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file1") MultipartFile file) {
        if (file.isEmpty()) {
            return "请选择文件";
        }
        try {
            FileInputStream fileInputStream = (FileInputStream) file.getInputStream();
            // 构造一个带指定Zone对象的配置类
            Configuration cfg = new Configuration(Zone.zone0());
            // 其他参数参考类注释
            UploadManager uploadManager = new UploadManager(cfg);
            // 生成上传凭证,然后准备上传
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucketName);

            String originalFilename = file.getOriginalFilename();
            String fileExtend = originalFilename.substring(originalFilename.lastIndexOf("."));
            //默认不指定key的情况下,以文件内容的hash值作为文件名
            String key = fileDir + UUID.randomUUID().toString().replace("-", "") + fileExtend;
            Response response = uploadManager.put(fileInputStream, key, upToken, null, null);
            // 解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            String returnPath = fileDomain + "/" + putRet.key;
            return returnPath;
        } catch (Exception e) {
            e.printStackTrace();
            return "上传失败";
        }
    }
}