阿里云OSS文件上传下载工具类

引入依赖

		<dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.1.0</version>
        </dependency>

配置文件

aliyun:
  oss:
    # 地域节点
    endPoint: 
    # Bucket 域名
    #    urlPrefix: 
    # accessKey Id
    accessKeyId: 
    # accessKey Secret
    accessKeySecret: 
    # 你的Bucket名称
    bucketName: 
    # 目标文件夹
    fileHost: 

工具类

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.qyzb.base.result.ResultCode;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @Author: cheng
 * @Date: 2022/8/15 9:24
 */
@Component
@Setter
@Getter
public class OSSUtils {

    private static String endPoint;
    private static String bucketName;
    private static String fileHost;

    @Value("${aliyun.oss.endPoint}")
    private String endpoint;

    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucketName}")
    private String bucketname;

    @Value("${aliyun.oss.fileHost}")
    private String filehost;

    static OSS ossClient;

    @PostConstruct
    public void initClient(){
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        endPoint = this.endpoint;
        bucketName = this.bucketname;
        fileHost = this.filehost;
    }

    /**
     * 文件上传
     * @param: uploadFile
     */
    public static String upload(MultipartFile uploadFile) {
        String returnImgeUrl = "";

        // 获取文件原名称
        String originalFilename = uploadFile.getOriginalFilename();

        //获取当前时间戳
        long l = System.currentTimeMillis();
        // 文件名
        String newFileName = l + "_" + originalFilename;

        // 文件上传的路径地址
        String uploadUrl = fileHost + "/" + newFileName;

        // 获取文件输入流
        InputStream inputStream = null;
        try {
            inputStream = uploadFile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //文件上传至阿里云OSS
        ossClient.putObject(bucketName, uploadUrl, inputStream);

        //注意:在实际项目中,文件上传成功后,数据库中存储文件地址
        // 获取文件上传后的图片返回地址
        returnImgeUrl = "http://" + bucketName + "." + endPoint + "/" + uploadUrl;

        return newFileName;
    }

    /**
     * 文件下载
     * @param: fileName
     * @param: outputStream
     */
    public static String download(String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
//        // 设置响应头为下载
//        response.setContentType("application/x-download");
//        // 设置下载的文件名
//        response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
//        response.setCharacterEncoding("UTF-8");

        // 文件名以附件的形式下载
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

        String fileKey = fileHost + "/" + fileName;
        // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
        OSSObject ossObject = ossClient.getObject(bucketName, fileKey);
        try {
            // 读取文件内容。
            InputStream inputStream = ossObject.getObjectContent();
            // 把输入流放入缓存流
            BufferedInputStream in = new BufferedInputStream(inputStream);
            ServletOutputStream outputStream = response.getOutputStream();
            // 把输出流放入缓存流
            BufferedOutputStream out = new BufferedOutputStream(outputStream);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
            out.close();
            in.close();
            return ResultCode.SUCCESS.message();
        } catch (Exception e) {
            return ResultCode.ERROR.message();
        }
    }

    public static String getObjectByte(String url) throws Exception {
        String fileKey = fileHost + "/" + url;
        // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
        OSSObject ossObject = ossClient.getObject(bucketName, fileKey);
        byte[] buffer = new byte[1024];
        StringBuilder sb = new StringBuilder();
        try {
            // 读取文件内容。
            InputStream inputStream = ossObject.getObjectContent();
            int i = 0;
            while ((i = inputStream.read(buffer)) != -1) {
                sb.append(new String(buffer, 0, i));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * 文件删除
     * @param: objectName
     */
    public static String delete(String fileName) {
        try {
            /*
             * 注意:在实际项目中,不需要删除OSS文件服务器中的文件,
             * 只需要删除数据库存储的文件路径即可!
             */
            // 根据BucketName,fileName删除文件
            // 删除目录中的文件,如果是最后一个文件fileoath目录会被删除。
            String fileKey = fileHost + "/" + fileName;
            ossClient.deleteObject(bucketName, fileKey);

            System.out.println("文件删除!");
            return ResultCode.SUCCESS.message();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultCode.ERROR.message();
        }
    }


}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个基于Java的图片上传工具类的示例代码: ```java import java.io.File; import java.io.IOException; import java.util.UUID; import org.springframework.web.multipart.MultipartFile; public class ImageUploadUtil { public static String uploadImage(MultipartFile file, String uploadPath) { // 生成新的文件名 String fileName = UUID.randomUUID().toString() + getFileSuffix(file.getOriginalFilename()); // 创建文件对象 File dest = new File(uploadPath + "/" + fileName); // 判断目录是否存在,不存在则创建 if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } try { // 保存文件 file.transferTo(dest); // 返回文件名 return fileName; } catch (IOException e) { e.printStackTrace(); return null; } } // 获取文件后缀 private static String getFileSuffix(String fileName) { return fileName.substring(fileName.lastIndexOf(".")); } } ``` 该工具类使用了Java的File类和MultipartFile类,其中getFileSuffix()方法用于获取上传文件的后缀名,而uploadImage()方法则接收一个MultipartFile类型的文件,将其转换为File类型并保存到指定的目录下,并返回文件名。 在使用时,可以将该工具类直接复制到项目中,并在需要上传图片的地方调用uploadImage()方法即可。例如,在Spring MVC中,可以在Controller中编写如下代码: ```java @PostMapping("/uploadImage") @ResponseBody public String uploadImage(@RequestParam("file") MultipartFile file) { String uploadPath = "E:/upload"; String fileName = ImageUploadUtil.uploadImage(file, uploadPath); return fileName; } ``` 其中,@PostMapping注解用于处理POST请求,@RequestParam注解用于接收上传的文件。在方法中,调用ImageUploadUtil.uploadImage()方法上传文件,并将上传后的文件名返回给前端。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值