Site Overlay

WebFlux中使用阿里云OSS文件上传

需求:上传图片返回地址。(WebFlux下)

导入依赖:

  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
  </dependency>
  <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
  </dependency>
  <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
  </dependency>

OssUtil:

@Component
public class OssUtil {

    private String endpoint="你的oss地址";
    private String accessKeyId="你的accessKeyId";
    private String accessKeySecret="你的accessKeySecret";
    private String bucketName="mrk";  //容器名

    private OSSClient ossClient=new OSSClient(endpoint, accessKeyId, accessKeySecret);

    public String updateHead(InputStream instream, String fileName){
        try {
            ossClient.putObject(bucketName,fileName,instream);
        } catch (Exception e) {
           return "false";
        }
        return "https://"+bucketName+".oss-cn-hangzhou.aliyuncs.com/"+fileName;
    }
}

Controller层与Service层根据自己的业务逻辑进行编写,在webFlux下主要就是传过来的接收方式需要注意,协商前台通过form-data表单进行提交,OssClent接受的是inputStrem流,Controller层在server-web包下一般会使用@requestParm接收 MultipartFile 文件进行转流处理,在WebFlux下则采用@requestPart来接收:

//controller层
@RequestMapping(value = "/uploadhead")
    public Object requestBodyFlux(@RequestPart("file")FilePart file, @RequestPart("账号")String name,@RequestPart("token")String token) {
        log.info("files:{}",file);
        retruen Service.loadFlie(file);
}
//service层
    /**
     * 设置头像
     *
     * @param filePart 头像文件
     * @return 头像地址
     */
    public Object uploadhead(FilePart filePart) throws IOException {
        Path tempFile = Files.createTempFile("head", filePart.filename());
        filePart.transferTo(tempFile.toFile()).subscribe();
        File file = tempFile.toFile();
        FileInputStream fileInputStream = new FileInputStream(file);
        String fileName = "headPic" + UUID.randomUUID() + ".png";
        String folder = "head";
        String url = ossUtil.updateHead(fileInputStream, folder + "/" + fileName);
        if ("false".equals(url)) {
              return "图片上传失败";
           } else {
              user1.setHead(url);
              userRedisDao.save(user1);
              return url;
           }
    }

如果不出意外地话,接收正常,返回也会正常,但意外不出来的话就不叫意外的,总会有意料之外的情况,如果有前台通过@requestParm或者@requestPart传文件都接收不了的情况,就得自己从请求里面取了,相对就麻烦一点,手动取参方法在之后的文章中会说明。

文章:在WebFlux下从ServerWebExchange中获取参数

发表回复

您的电子邮箱地址不会被公开。

A beliving heart is your magic My heart
欢迎来到Diuut的个人博客,这里是我的一些零零碎碎的知识汇总,希望有能帮到你的内容。 | 蜀ICP备2021011635号-1 | Copyright © 2024 Diuut. All Rights Reserved.