阿里雲oss文件存儲


package com.cqcfs.storage.oss.service;

import java.io.InputStream;

/**
 * 文件上傳接口
 *
 * @author kongweichun
 * @date 2017-12-14-上午10:45
 */
public interface FileStorage{

    /**
     * 上傳文件
     *
     * @param fileBytes 文件的字節數組
     * @param key       文件名
     * @return 文件標識的唯一id
     * @author LIQIU
     * @Date 2017/12/14 上午11:28
     */
    void store(byte[] fileBytes, String key);

    /**
     * 存儲輸入流
     *
     * @param input
     * @param key
     */
    void store(InputStream input, String key);

    /**
     * 下載文件
     *
     * @param key 文件名(帶后綴名的)
     * @author LIQIU
     * @Date 2017/12/14 上午11:28
     */
    byte[] getBytes(String key);

    /**
     * 通過KEY刪除文件
     *
     * @param key
     */
    void remove(String key);

    /**
     * 獲取輸入流
     *
     * @param key
     * @return
     */
    InputStream getInputStream(String key);

    /**
     * 獲取下載鏈接
     *
     * @param key
     * @return
     */
    String getDownloadUrl(String key);

}
package com.cqcfs.storage.oss.service.imp;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.BucketInfo;
import com.aliyun.oss.model.OSSObject;
import com.cqcfs.storage.oss.service.FileStorage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PreDestroy;
import java.io.*;

/**
 * 阿里雲文件上傳
 *
 * @author kongweichun
 * @date 2017-12-14-上午10:53
 */
@Service
public class AliyunFileStorage implements FileStorage {

    @Value("${aliyun.file.storage.accesssKey}")
    private String accessKey;
    @Value("${aliyun.file.storage.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.file.storage.endpoint}")
    private String endpoint;

    /**
     * oss的bucket名稱
     */
    private String bucketName = "cqcfs-iot";


    private OSSClient getOssClient(){
        return new OSSClient(endpoint, accessKey, accessKeySecret);
    }

    /**
     * 文件上傳
     * @param fileBytes 文件的字節數組
     * @param key       文件名
     */
    @Override
    public void store(byte[] fileBytes, String key) {
        getOssClient().putObject(bucketName, key, new ByteArrayInputStream(fileBytes));
    }

    /**
     * 圖片上傳
     * @param input
     * @param key
     */
    @Override
    public void store(InputStream input, String key) {
        getOssClient().putObject(bucketName, key, input);
    }


    /**
     * 文件下載
     * @param key 文件名(帶后綴名的)
     * @return
     */
    @Override
    public byte[] getBytes(String key) {
        OSSObject ossObject = getOssClient().getObject(bucketName, key);
        BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));
        byte[] buf = new byte[1024];
        InputStream in = ossObject.getObjectContent();
        for (int n = 0; n != -1; ) {
            try {
                n = in.read(buf, 0, buf.length);
            } catch (IOException e) {
                throw new RuntimeException("download file error!");
            }
        }
        try {
            in.close();
            reader.close();
        } catch (IOException e) {
            throw new RuntimeException("download file error!");
        }
        return buf;
    }

    /**
     * 刪除文件
     * @param key 文件名
     */
    @Override
    public void remove(String key) {
        getOssClient().deleteObject(bucketName, key);
    }

    /**
     * 圖片下載
     * @param key 文件名
     * @return
     */
    @Override
    public InputStream getInputStream(String key) {
        return getOssClient().getObject(bucketName, key).getObjectContent();
    }

    /**
     * 獲取文件下載地址
     * @param key 文件名
     * @return
     */
    @Override
    public String getDownloadUrl(String key) {
        BucketInfo bucketInfo = getOssClient().getBucketInfo(this.getBucketName());
        Bucket bucket = bucketInfo.getBucket();
        return  "http://" + bucket.getName() + "." + bucket.getExtranetEndpoint() + "/" + key;
    }


    public String getBucketName() {
        return bucketName;
    }

    public void setBucketName(String bucketName) {
        this.bucketName = bucketName;
    }

    @PreDestroy
    public void destroy() {
        getOssClient().shutdown();
    }
}
package com.cqcfs.storage.oss.server;

import com.cqcfs.framework.common.protocol.Result;
import com.cqcfs.storage.oss.model.MeterialUploadForm;
import com.cqcfs.storage.oss.service.FileStorage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;

/**
 * @author kongweichun
 * @since 2019/3/25
 */
@RestController
@RequestMapping("/file")
@Api(value = "/file" , tags = "文件管理")
public class AliyunFileStorageResource {
    @Autowired
    FileStorage fileStorage;

    @PostMapping("v1/upload")
    @ApiOperation(value = "文件上傳")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "form", dataType="file", name = "file", value = "文件", required = true),
            @ApiImplicitParam(paramType = "query",dataType = "String",name = "key",value = "文件名稱",required = true)
    })
    public Result upload(MeterialUploadForm form, @RequestParam("key") String key)throws Exception{
        if (form.getFile() != null){
            byte[] bytes = form.getFile().getBytes();
            fileStorage.store(bytes,key);
            return Result.buildSuccess("OK");
        }
        return Result.buildFailure(70001,"文件為空");
    }


    @PostMapping("v1/upload/img")
    @ApiOperation(value = "圖片上傳")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "form", dataType="file", name = "file", value = "文件", required = true),
            @ApiImplicitParam(paramType = "query",dataType = "String",name = "key",value = "文件名稱",required = true)
    })
    public Result uploadImg(MeterialUploadForm form, @RequestParam("key") String key)throws Exception{
        if (form.getFile() != null){
            InputStream input = form.getFile().getInputStream();
            fileStorage.store(input,key);
            return Result.buildSuccess("OK");
        }
        return Result.buildFailure(70001,"文件為空");
    }


    @PostMapping("v1/get")
    @ApiOperation(value = "文件下載")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",dataType = "String",name = "key",value = "文件名稱",required = true)
    })
    public Result get(@RequestParam("key")String key){
        byte[] bytes = fileStorage.getBytes(key);
        return Result.buildSuccess(bytes);
    }


    @PostMapping("v1/remove")
    @ApiOperation(value = "文件刪除")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",dataType = "String",name = "key",value = "文件名稱",required = true)
    })
    public Result remove(@RequestParam("key")String key){
        fileStorage.remove(key);
        return Result.buildSuccess("OK");
    }


    @PostMapping("v1/get/inp")
    @ApiOperation(value = "獲取輸入流")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",dataType = "String",name = "key",value = "文件名稱",required = true)
    })
    public Result getInp(@RequestParam("key")String key){
        InputStream inputStream = fileStorage.getInputStream(key);
        return Result.buildSuccess(inputStream);
    }


    @PostMapping("v1/get/url")
    @ApiOperation(value = "獲取下載URL")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",dataType = "String",name = "key",value = "文件名稱",required = true)
    })
    public Result getUrl(String key){
        String url = fileStorage.getDownloadUrl(key);
        return Result.buildSuccess(url);
    }

}
package com.cqcfs.storage.oss.model;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author kongweichun
 * @since 2019/3/26
 */
@Data
@ApiModel(description = "材料上傳form")
public class MeterialUploadForm {

    @ApiModelProperty("材料文件")
    private MultipartFile file;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM