Springboot从前端获取文件上传到七牛云,

controller类

    public String upload(@RequestParam("uploadFile") MultipartFile uploadFile) throws IOException {
        String fileName = uploadFile.getOriginalFilename();
        System.out.println(fileName);
        fileName = fileName.substring(0, fileName.lastIndexOf("."));
        if (uploadFile.isEmpty()) {
            return "上传失败,无法找到图片!";
        }else {
            String QNUrl = QiniuUtils.uploadQNImg(uploadFile);
            return "上传成功:"+QNUrl;
        }
        //return "上传失败";
    }

工具包:七牛云

 * 七牛云上传工具包
 */
public class QiniuUtils {
    @Value("${qiniu.accessKey}")
    private static String accessKey;
    @Value("${qiniu.secretKey}")
    private static String secretKey;
    @Value("${qiniu.bucket}")
    private static String bucket;
    @Value("${qiniu.domain")
    private static String domain;

    public static String uploadQNImg(MultipartFile file){
        Configuration cfg = new Configuration(Region.region2());
//...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        String key = getRandomCharacterAndNumber(10) + ".png";//生成随机文件名
        String responseUrl="";
        try {
            Response response = uploadManager. put(file.getInputStream(), key, upToken,null,null);
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
           responseUrl= responseUrl+domain+"/"+putRet.key;

        } catch (QiniuException e) {
            Response r = e.response;
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseUrl;
    }

    /**
     *  生成随机图片的名字
     * @param length 名字的长度
     * @return
     */
    public static String getRandomCharacterAndNumber(int length) {
        String val = "";
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; // 输出字母还是数字

            if ("char".equalsIgnoreCase(charOrNum)) // 字符串
            {
                int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; // 取得大写字母还是小写字母
                val += (char) (choice + random.nextInt(26));
                // int choice = 97; // 指定字符串为小写字母
                val += (char) (choice + random.nextInt(26));
            } else if ("num".equalsIgnoreCase(charOrNum)) // 数字
            {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }
}

你可能感兴趣的:(Springboot从前端获取文件上传到七牛云,)