首页 > 其他分享 >阿里云OSS文件上传

阿里云OSS文件上传

时间:2023-03-06 13:13:41浏览次数:40  
标签:String objectName com OSS 阿里 bucketName error import 上传

阿里OSS文件上传

Controller
package com.zft.web.controller.common;

import com.zft.adaptor.common.constants.FileConstants;
import com.zft.adaptor.utils.file.CompressUtil;
import com.zft.adaptor.utils.file.FileTypeUtil;
import com.zft.domain.service.common.FileService;
import com.zft.domain.service.common.dto.FileAddressDto;
import com.zft.web.common.BaseResponse;
import com.zft.domain.common.HttpStatus;
import com.zft.web.common.ResultBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Objects;

/**
 * @author life
 * Create on 2023/2/11.
 */
@Slf4j
@RestController
@RequestMapping(path = "/api/file/V1.0", produces = "application/json")
public class FileController {

    @Autowired
    private FileService fileService;

    @PostMapping("/uploadFile")
    public BaseResponse<FileAddressDto> uploadFile(MultipartFile file) {
        String filename = file.getOriginalFilename();
        if (Objects.isNull(filename)) {
            return ResultBuilder.buildErrorResult(HttpStatus.PARAM_ERROR_REQUIRED);
        }
        try {
            byte[] bytes = file.getBytes();
            String objectName = CompressUtil.getPath(filename);
            FileAddressDto addressDto;
            if (FileTypeUtil.isPhoto(filename)) {
                // 考虑成本压缩文件 调用图片压缩方法
                bytes = CompressUtil.compressPicForScale(bytes, CompressUtil.MAX_SIZE);
                InputStream inputStream = new ByteArrayInputStream(bytes);
                addressDto = fileService.uploadPhotoFile(FileConstants.BUCKET_NAME, objectName, inputStream);
            } else {
                InputStream inputStream = new ByteArrayInputStream(bytes);
                addressDto = fileService.uploadPhotoFile(FileConstants.BUCKET_NAME, objectName, inputStream);
            }
            return ResultBuilder.buildSuccessResult(addressDto);
        } catch (Exception e) {
            log.error("FileController uploadFile error", e);
            return ResultBuilder.buildErrorResult(HttpStatus.FILE_ERROR_UPLOAD);
        }
    }

    @PostMapping(value = "/downloadFile", produces = {MediaType.APPLICATION_OCTET_STREAM_VALUE, MediaType.APPLICATION_JSON_VALUE})
    public BaseResponse<Object> downloadFile(String fileName, HttpServletRequest request, HttpServletResponse response) {
        if (Objects.isNull(fileName)) {
            return ResultBuilder.buildErrorResult(HttpStatus.PARAM_ERROR_REQUIRED);
        }
        InputStream inputStream = null;
        BufferedOutputStream outputStream = null;
        try {
            inputStream = fileService.downloadFile(FileConstants.BUCKET_NAME, fileName);
            response.reset();
            response.setHeader("Content-disposition", "attachment;filename=" + setFileDownloadHeader(request, fileName));
            response.setContentType("application/octet-stream;charset=UTF-8");
            outputStream = new BufferedOutputStream(response.getOutputStream());
            if (inputStream != null) {
                int len;
                while ((len = inputStream.read()) != -1) {
                    outputStream.write(len);
                    outputStream.flush();
                }
            }
        } catch (Exception e) {
            log.error("FileController downloadFile error", e);
            return ResultBuilder.buildErrorResult(HttpStatus.FILE_ERROR_UPLOAD);
        } finally {
            if (Objects.nonNull(inputStream)) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (Objects.nonNull(outputStream)) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException {
        final String agent = request.getHeader("USER-AGENT");
        String filename = fileName;
        if (agent.contains("MSIE")) {
            // IE浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        } else if (agent.contains("Firefox")) {
            // 火狐浏览器
            filename = new String(fileName.getBytes(), "ISO8859-1");
        } else if (agent.contains("Chrome")) {
            // google浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        } else {
            // 其它浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }
}


Service
业务层接口
package com.zft.domain.service.common;

import com.zft.adaptor.common.exception.BusinessException;
import com.zft.domain.service.common.dto.FileAddressDto;

import java.io.InputStream;

/**
 * @author life
 * Create on 2023/2/11.
 */
public interface FileService {

    /**
     * 创建Bucket
     *
     * @param bucketName Bucket名称
     */
    String createBucket(String bucketName) throws BusinessException;

    /**
     * 上传图片文件
     *
     * @param inputStream 文件流
     * @param bucketName  Bucket名称
     * @param objectName  Object完整路径,例如exampledir/exampleobject.txt
     */
    FileAddressDto uploadPhotoFile(String bucketName, String objectName, InputStream inputStream) throws BusinessException;

    /**
     * 上传非图片文件
     *
     * @param inputStream 文件流
     * @param bucketName  Bucket名称
     * @param objectName  Object完整路径,例如exampledir/exampleobject.txt
     */
    void uploadFile(String bucketName, String objectName, InputStream inputStream) throws BusinessException;

    /**
     * 下载文件
     *
     * @param bucketName Bucket名称
     * @param objectName Object完整路径,例如exampledir/exampleobject.txt
     */
    InputStream downloadFile(String bucketName, String objectName) throws BusinessException;
}

业务层实现
package com.zft.domain.service.common.impl;

import com.zft.adaptor.common.exception.BusinessException;
import com.zft.adaptor.rpc.AliYunOssService;
import com.zft.domain.service.common.FileService;
import com.zft.domain.service.common.convertor.FileConvertor;
import com.zft.domain.service.common.dto.FileAddressDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;

/**
 * @author life
 * Create on 2023/2/11.
 */
@Slf4j
@Service("fileService")
public class FileServiceImpl implements FileService {

    @Autowired
    private AliYunOssService aliYunOssService;

    @Override
    public String createBucket(String bucketName) throws BusinessException {
        return aliYunOssService.createBucket(bucketName);
    }

    @Override
    public FileAddressDto uploadPhotoFile(String bucketName, String objectName, InputStream inputStream) throws BusinessException {
        return FileConvertor.INSTANCE.do2Dto(aliYunOssService.uploadPhotoFile(bucketName, objectName, inputStream));
    }

    @Override
    public void uploadFile(String bucketName, String objectName, InputStream inputStream) throws BusinessException {
        aliYunOssService.uploadFile(bucketName, objectName, inputStream);
    }

    @Override
    public InputStream downloadFile(String bucketName, String objectName) throws BusinessException {
        return aliYunOssService.downloadFile(bucketName, objectName);
    }
}

阿里接口
package com.zft.adaptor.rpc;

import com.zft.adaptor.common.exception.BusinessException;
import com.zft.adaptor.rpc.dto.FileAddressDo;

import java.io.InputStream;

/**
 * @author life
 * Create on 2023/2/11.
 */
public interface AliYunOssService {

    /**
     * 创建Bucket
     *
     * @param bucketName Bucket名称
     */
    String createBucket(String bucketName) throws BusinessException;

    /**
     * 上传图片文件
     *
     * @param inputStream 文件流
     * @param bucketName  Bucket名称
     * @param objectName  Object完整路径,例如exampledir/exampleobject.txt
     */
    FileAddressDo uploadPhotoFile(String bucketName, String objectName, InputStream inputStream) throws BusinessException;

    /**
     * 上传非图片文件
     *
     * @param inputStream 文件流
     * @param bucketName  Bucket名称
     * @param objectName  Object完整路径,例如exampledir/exampleobject.txt
     */
    void uploadFile(String bucketName, String objectName, InputStream inputStream) throws BusinessException;

    /**
     * 下载文件
     *
     * @param bucketName Bucket名称
     * @param objectName Object完整路径,例如exampledir/exampleobject.txt
     */
    InputStream downloadFile(String bucketName, String objectName) throws BusinessException;
}

阿里实现
package com.zft.adaptor.rpc.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.zft.adaptor.common.exception.BusinessException;
import com.zft.adaptor.rpc.AliYunOssService;
import com.zft.adaptor.rpc.dto.FileAddressDo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.Date;

/**
 * @author life
 * Create on 2023/2/10.
 */
@Slf4j
@Service("aliYunOssService")
public class AliYunOssServiceImpl implements AliYunOssService {

    private final static String ENDPOINT = "https://*********.com";
    private final static String ACCESS_KEY_ID = "*********";
    private final static String ACCESS_KEY_SECRET = "*********";

    @Override
    public String createBucket(String bucketName) throws BusinessException {
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        try {
            ossClient.createBucket(bucketName);
        } catch (OSSException oe) {
            log.error("Caught an OSSException, which means your request made it to OSS, but was rejected with an error response for some reason.");
            log.error("Error Message:" + oe.getErrorMessage());
            log.error("Error Code:" + oe.getErrorCode());
            log.error("Request ID:" + oe.getRequestId());
            log.error("Host ID:" + oe.getHostId());
            throw new BusinessException("创建Bucket" + oe.getMessage());
        } catch (ClientException ce) {
            log.error("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            log.error("Error Message:" + ce.getMessage());
            throw new BusinessException("创建Bucket" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return bucketName;
    }

    @Override
    public FileAddressDo uploadPhotoFile(String bucketName, String objectName, InputStream inputStream) throws BusinessException {
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        try {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType(getContentType(objectName.substring(objectName.lastIndexOf("."))));
            ossClient.putObject(bucketName, objectName, inputStream, objectMetadata);
            Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
            String url = ossClient.generatePresignedUrl(bucketName, objectName, expiration).toString();
            return FileAddressDo.builder().fileUrl(url).objectName(objectName).build();
        } catch (OSSException oe) {
            log.error("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            log.error("Error Message:" + oe.getErrorMessage());
            log.error("Error Code:" + oe.getErrorCode());
            log.error("Request ID:" + oe.getRequestId());
            log.error("Host ID:" + oe.getHostId());
            throw new BusinessException("文件上传失败" + oe.getMessage());
        } catch (ClientException ce) {
            log.error("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            log.error("Error Message:" + ce.getMessage());
            throw new BusinessException("文件上传失败" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    @Override
    public void uploadFile(String bucketName, String objectName, InputStream inputStream) throws BusinessException {
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        try {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType(getContentType(objectName.substring(objectName.lastIndexOf("."))));
            ossClient.putObject(bucketName, objectName, inputStream, objectMetadata);
            Date expiration = new Date(System.currentTimeMillis() + 315360000L * 1000);
            String url = ossClient.generatePresignedUrl(bucketName, objectName, expiration).toString();
            log.info(url);
        } catch (OSSException oe) {
            log.error("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            log.error("Error Message:" + oe.getErrorMessage());
            log.error("Error Code:" + oe.getErrorCode());
            log.error("Request ID:" + oe.getRequestId());
            log.error("Host ID:" + oe.getHostId());
            throw new BusinessException("文件上传失败" + oe.getMessage());
        } catch (ClientException ce) {
            log.error("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            log.error("Error Message:" + ce.getMessage());
            throw new BusinessException("文件上传失败" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    @Override
    public InputStream downloadFile(String bucketName, String objectName) throws BusinessException {
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        try {
            if (!ossClient.doesObjectExist(bucketName, objectName)) {
                throw new BusinessException("文件不存在");
            }
            // 调用ossClient.getObject返回一个OSSObject实例,该实例包含文件内容及文件元信息。
            OSSObject ossObject = ossClient.getObject(bucketName, objectName);
            // 调用ossObject.getObjectContent获取文件输入流,可读取此输入流获取其内容。
            InputStream content = ossObject.getObjectContent();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = content.read(buffer)) > -1) {
                outputStream.write(buffer, 0, len);
            }
            // 数据读取完成后,获取的流必须关闭,否则会造成连接泄漏,导致请求无连接可用,程序无法正常工作。
            outputStream.flush();
            outputStream.close();
            content.close();
            return new ByteArrayInputStream(outputStream.toByteArray());
        } catch (OSSException oe) {
            log.error("Caught an OSSException, which means your request made it to OSS, but was rejected with an error response for some reason.");
            log.error("Error Message:" + oe.getErrorMessage());
            log.error("Error Code:" + oe.getErrorCode());
            log.error("Request ID:" + oe.getRequestId());
            log.error("Host ID:" + oe.getHostId());
            throw new BusinessException("文件下载失败" + oe.getMessage());
        } catch (ClientException ce) {
            log.error("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            log.error("Error Message:" + ce.getMessage());
            throw new BusinessException("文件下载失败" + ce.getMessage());
        } catch (IOException e) {
            log.error("AliYunOssServiceImpl downloadFile", e);
            throw new BusinessException("文件下载失败" + e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    private static String getContentType(String FilenameExtension) {
        if (".bmp".equalsIgnoreCase(FilenameExtension)) {
            return "image/bmp";
        }
        if (".gif".equalsIgnoreCase(FilenameExtension)) {
            return "image/gif";
        }
        if (".jpeg".equalsIgnoreCase(FilenameExtension) ||
                ".jpg".equalsIgnoreCase(FilenameExtension) ||
                ".png".equalsIgnoreCase(FilenameExtension)) {
            return "image/jpg";
        }
        if (".html".equalsIgnoreCase(FilenameExtension)) {
            return "text/html";
        }

        if (".txt".equalsIgnoreCase(FilenameExtension)) {
            return "text/plain";
        }
        if (".vsd".equalsIgnoreCase(FilenameExtension)) {
            return "application/vnd.visio";
        }
        if (".pptx".equalsIgnoreCase(FilenameExtension) ||
                ".ppt".equalsIgnoreCase(FilenameExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        if (".docx".equalsIgnoreCase(FilenameExtension) ||
                ".doc".equalsIgnoreCase(FilenameExtension)) {
            return "application/msword";
        }
        if (".xml".equalsIgnoreCase(FilenameExtension)) {
            return "text/xml";
        }
        return "image/jpg";
    }
}

图片压缩
package com.zft.adaptor.utils.file;

import com.zft.adaptor.utils.date.DatePattern;
import com.zft.adaptor.utils.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.UUID;

/**
 * 图片压缩
 *
 * @author life
 * Create on 2023/2/11.
 */
@Slf4j
public class CompressUtil {

    public static final Integer MAX_SIZE = 200;
    private static final Integer ZERO = 0;
    private static final Integer ONE_ZERO_TWO_FOUR = 1024;
    private static final Integer NINE_ZERO_ZERO = 900;
    private static final Integer THREE_TWO_SEVEN_FIVE = 3275;
    private static final Integer TWO_ZERO_FOUR_SEVEN = 2047;
    private static final Double ZERO_EIGHT_FIVE = 0.85;
    private static final Double ZERO_SIX = 0.6;
    private static final Double ZERO_FOUR_FOUR = 0.44;
    private static final Double ZERO_FOUR = 0.4;

    /**
     * 根据指定大小压缩图片
     *
     * @param imageBytes  源图片字节数组
     * @param desFileSize 指定图片大小,单位kb
     * @return 压缩质量后的图片字节数组
     */
    public static byte[] compressPicForScale(byte[] imageBytes, long desFileSize) {
        if (imageBytes == null || imageBytes.length <= ZERO || imageBytes.length < desFileSize * ONE_ZERO_TWO_FOUR) {
            return imageBytes;
        }
        long srcSize = imageBytes.length;
        double accuracy = getAccuracy(srcSize / ONE_ZERO_TWO_FOUR);
        try {
            while (imageBytes.length > desFileSize * ONE_ZERO_TWO_FOUR) {
                ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length);
                Thumbnails.of(inputStream)
                        .scale(accuracy)
                        .outputQuality(accuracy)
                        .toOutputStream(outputStream);
                imageBytes = outputStream.toByteArray();
            }
            log.info("图片原大小={}kb | 压缩后大小={}kb", srcSize / ONE_ZERO_TWO_FOUR, imageBytes.length / ONE_ZERO_TWO_FOUR);
        } catch (Exception e) {
            log.error("【图片压缩】msg=图片压缩失败!", e);
        }
        return imageBytes;
    }

    /**
     * 自动调节精度(经验数值)
     *
     * @param size 源图片大小
     * @return 图片压缩质量比
     */
    private static double getAccuracy(long size) {
        double accuracy;
        if (size < NINE_ZERO_ZERO) {
            accuracy = ZERO_EIGHT_FIVE;
        } else if (size < TWO_ZERO_FOUR_SEVEN) {
            accuracy = ZERO_SIX;
        } else if (size < THREE_TWO_SEVEN_FIVE) {
            accuracy = ZERO_FOUR_FOUR;
        } else {
            accuracy = ZERO_FOUR;
        }
        return accuracy;
    }

    /**
     * 图片路径
     */
    public static String getPath(String fileName) {
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        return DateUtil.getNowDateString(DatePattern.PURE_DATE_PATTERN) + "/" + UUID.randomUUID() + suffix;
    }
}

标签:String,objectName,com,OSS,阿里,bucketName,error,import,上传
From: https://www.cnblogs.com/ChenQ2/p/17183463.html

相关文章

  • 文件上传
    文件上传packagecom.example.demo.base.file;importjava.io.*;importjava.net.URLDecoder;importjava.net.URLEncoder;importjava.time.LocalDateTime;import......
  • ASP.NET上传文件夹的三种解决方案
    ​ 以ASP.NETCoreWebAPI 作后端 API ,用 Vue 构建前端页面,用 Axios 从前端访问后端 API,包括文件的上传和下载。 准备文件上传的API #region 文件上传......
  • PHP上传文件夹的三种解决方案
    ​ PHP用超级全局变量数组$_FILES来记录文件上传相关信息的。1.file_uploads=on/off 是否允许通过http方式上传文件2.max_execution_time=30 允许脚本最大执行时......
  • 阿里云redis安装
    关于如何在linux环境下安装redis在此不在多说,自行百度。该文章主要说一些主要配置,让redis客户端能够连接redis服务器。如果虚拟机是在云服务器上,注意事项需要在云服务......
  • arXiv上传预印本(pre-printer)流程
    1.Start:使用邮箱注册账号(最好使用学生邮箱/校园邮箱:[email protected])。使用校园邮箱可以免老带新认证。2.Start->Addfiles:使用.tex上传->如果pdfLatex编译,则在......
  • ueditor 上传图片去掉高度属性方法
    在下面代码中查找setsize参数即可将height属性默认添加改为自定义是否添加,勾选设置图高单选框才添加image.html<!doctypehtml><html><head><metacharset="UTF-8"......
  • 动漫网盘阿里云
    猪侠全季+番外片+大电影合集全1080p修复版超高清登录以回复 最早内容1/2条一月2023 最新回复胖胖龙猫组合胖胖龙猫组合 2022年7月3日注册于2021年11月13日......
  • DVWA 之 File Upload-文件上传
    五、FileUpload-文件上传文件上传漏洞,通常是由于对上传文件的类型、内容没有进行严格的过滤、检查,使得攻击者可以通过上传木马获取服务器的webshell权限,因此文件上传漏洞......
  • SpringMVC:文件上传下载如何实现?
      一、文件下载如果在响应时候没有设置响应头中的Content-Disposition属性,则会使用默认值inline,此时客户端访问静态资源的时候,能解析显示的就会解析显示,不能解析......
  • docker搭建maven私服(nexus3),整合springboot上传下载依赖
    一、前言我们在JavaWeb开发中必不可少的就是jar包管理-maven,在没有maven之前,都是自己手动下载jar包导入到项目中,非常的繁琐。maven出现之后,又迎来新的问题,对于仓库里人家......