springboot通过流的方式上传文件

该文章介绍了如何在SpringBoot应用中使用流处理方式上传文件。首先配置了文件存储的YML路径为/home/,接着检查并创建目标目录,然后读取多部分文件的字节,通过FileOutputStream和BufferedOutputStream将文件写入指定路径,过程中处理了可能的IOException。
摘要由CSDN通过智能技术生成

springboot通过流的方式上传文件

yml文件路径配置
file:
  path: /home/

代码

        File dir = new File(path);
        if (!dir.exists() && !dir.isDirectory()) {
            dir.mkdirs();
        }
        try {
            byte[] bytes = multipartFile.getBytes();
            File uploadFile = new File(path + "/" + fileName);
            FileOutputStream fos  = new FileOutputStream(uploadFile);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bos.write(bytes);
            bos.flush();
            bos.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
Spring Boot上传文件到阿里云OSS (Object Storage Service) 的程通常包括以下几个步骤: 1. 配置依赖:首先,在你的`pom.xml`中添加 Alibaba Cloud SDK 的依赖,比如 `spring-cloud-starter-alibaba-nacos-discovery` 和 `aliyun-sdk-core`。 ```xml <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-oss</artifactId> </dependency> ``` 2. 实现上传服务:创建一个 Spring Bean,例如 `OssService`,用于处理上传操作。这个类通常会包含一个构造函数接收OSS客户端实例,并封装 OSS 文件上传的方法。 ```java import com.aliyuncs.IAcsClient; import com.aliyuncs.OSSClientBuilder; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.exceptions.ServerException; public class OssService { private final IAcsClient ossClient; public OssService(String endpoint, String accessKeyId, String accessKeySecret, String bucketName) { this.ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); } public void uploadFileToOSS(InputStream inputStream, String objectKey) throws ClientException, ServerException { ossClient.putObject(bucketName, objectKey, inputStream); ossClient.shutdown(); } } ``` 3. 调用上传方法:在需要上传文件的地方,你可以注入 `OssService` 并调用 `uploadFileToOSS` 方法,传入文件和对象键(objectKey)。 ```java @Autowired private OssService ossService; public void uploadFileToOSS(File file, String fileName) { try (InputStream inputStream = new FileInputStream(file)) { ossService.uploadFileToOSS(inputStream, fileName); } catch (IOException e) { log.error("Failed to upload file", e); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

W先生'

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值