java获取前段的文件上传七牛云

package com.kangdang.qiniu01.controller;

import com.google.gson.Gson;

import com.qiniu.common.QiniuException;

import com.qiniu.http.Response;

import com.qiniu.storage.Configuration;

import com.qiniu.storage.Region;

import com.qiniu.storage.UploadManager;

import com.qiniu.storage.model.DefaultPutRet;

import com.qiniu.util.Auth;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.RestController;

import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController

public class TestController {

@Value("${qiniu.accessKey}")

private StringaccessKey;

    @Value("${qiniu.secretKey}")

private StringsecretKey;

    @Value("${qiniu.bucket}")

private Stringbucket;

    @RequestMapping(value ="/uploadTest", method = RequestMethod.POST)

public Stringupload(@RequestParam("uploadFile") MultipartFile uploadFile)throws IOException {

String fileName = uploadFile.getOriginalFilename();

        System.out.println(fileName);

        fileName = fileName.substring(0, fileName.lastIndexOf("."));

        if (uploadFile.isEmpty()) {

return "上传失败,无法找到文件!";

        }

if (qiniu(uploadFile,fileName)){

return "上传成功";}

return "上传失败";

    }

@RequestMapping(value ="/uploadsTest", method = RequestMethod.POST)

public Stringuploads(@RequestParam("uploadFile") MultipartFile[] uploadFiles)throws IOException {

if (uploadFiles==null || uploadFiles.length<1) {

return "上传失败,无法找到文件!";

        }

for (MultipartFile file:uploadFiles) {

String fileName = file.getOriginalFilename();

            System.out.println(fileName);

            fileName = fileName.substring(0, fileName.lastIndexOf("."));

            qiniu(file,fileName);

        }

return "上传成功";

    }

public boolean qiniu(MultipartFile inputStream,String key)throws IOException {

Configuration cfg =new Configuration(Region.region2());

//...其他参数参考类注释

        UploadManager uploadManager =new UploadManager(cfg);

        Auth auth = Auth.create(accessKey, secretKey);

        String upToken = auth.uploadToken(bucket);

        //byte[] bytes = inputStream.getBytes();

        try {

Response response = uploadManager. put(inputStream.getInputStream(), key, upToken,null,null);

            DefaultPutRet putRet =new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

            System.out.println(putRet.key);

            System.out.println(putRet.hash);

return true;

        }catch (QiniuException e) {

Response r = e.response;

            e.printStackTrace();

return false;

        }

}

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。