java 上传文件到七牛云

<dependency>
   <groupId>com.qiniu</groupId>
   <artifactId>qiniu-java-sdk</artifactId>

</dependency>

//java上传流文件,二进制流文件

 //java 七牛上传
@RequestMapping("/file")
public ResponseEntity<Object> sendQiniuFile(MultipartFile file) {
    Configuration cfg = new Configuration(Zone.zone0());
    UploadManager uploadManager = new UploadManager(cfg);
    String accessKey = "你自己的ak";
    String secretKey = "你自己的sk";
    String bucket = "你自己的bucket";
    DefaultPutRet putRet = null;
    try {
        //密钥配置
        String key = file.getOriginalFilename();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); 
//增加文件后缀名的时间戳
        String str = simpleDateFormat.format(new Date());
        String newKey = key.substring(0 ,key.indexOf(".")) + "-"+str + key.substring(key.lastIndexOf("."));
//例如:账号配置-20180201181253.xlsx
        InputStream inputStream = file.getInputStream();
        byte[] bytes = this.readStream(inputStream);
        ByteArrayInputStream byteInputStream = new ByteArrayInputStream(bytes);
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        Response res = uploadManager.put(byteInputStream ,newKey,upToken,null, null);
        //解析上传成功的结果
        putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
        System.out.println(putRet.key);
        System.out.println(putRet.hash);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ResponseUtil.success(putRet);
}

public static byte[] readStream(InputStream inStream) throws Exception{
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len = -1;
    while((len = inStream.read(buffer)) != -1){
        outStream.write(buffer, 0, len);
    }
    outStream.close();
    inStream.close();
    return outStream.toByteArray();
}

猜你喜欢

转载自blog.csdn.net/ccmedu/article/details/79235203