2022年最新《谷粒学院开发教程》:3 - 文件上传

2022年最新《谷粒学院开发教程》:3 - 文件上传,第1张

更好的阅读体验资料地址1 - 构建工程篇2 - 前后端交互篇

目录 一、阿里云OSS对象存储1.1、创建账户1.2、搭建文件上传模块1.3、实现文件上传 二、Nginx配置反向代理三、上传讲师头像


一、阿里云OSS对象存储 1.1、创建账户

1、创建 bucket

2、创建子账户

一般在公司中,我们没有权限可以直接 *** 作公司的阿里云账户,所以我们需要获取创建阿里云OSS许可证(阿里云颁布id和秘钥)

3、创建子账户

AccessKeyID: LTAI5tL5FrVJBuQadij4KRvJ
AccessKeySecret: Xs7dHUvxCdHLd0K5iFK7NWEbdUN7GG

1.2、搭建文件上传模块

1、新建 service_oss Maven模块 (父模块为 service)

2、POM


<dependency>
    <groupId>com.aliyun.ossgroupId>
    <artifactId>aliyun-sdk-ossartifactId>
dependency>

<dependency>
    <groupId>joda-timegroupId>
    <artifactId>joda-timeartifactId>
dependency>

3、properties

# 服务端口
server.port=8002

# 服务名
spring.application.name=service-oss

# 环境设置:dev、test、prod
spring.profiles.active=dev

# 阿里云 OSS
aliyun.oss.file.endpoint=oss-cn-guangzhou.aliyuncs.com
aliyun.oss.file.keyid=LTAI5tL5FrVJBuQadij4KRvJ
aliyun.oss.file.keysecret=Xs7dHUvxCdHLd0K5iFK7NWEbdUN7GG
aliyun.oss.file.bucketname=gulicollege-laptoy

4、启动类

package com.laptoy.oss;

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@ComponentScan(basePackages = {"com.laptoy"})
public class OssApplication {
    public static void main(String[] args) {
        SpringApplication.run(OssApplication.class, args);
    }
}

1.3、实现文件上传

1、业务层

public interface OssService {
    String uploadFileAvatar(MultipartFile file);
}

@Service
public class OssServiceImpl implements OssService {

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

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

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

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

    @Override
    public String uploadFileAvatar(MultipartFile file) {
        InputStream inputStream = null;
        try {
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 获取上传文件的输入流
            inputStream = file.getInputStream();
            //获取文件名称
            String fileName = file.getOriginalFilename();
            //调用oss实例中的方法实现上传
            ossClient.putObject(bucketName, fileName, inputStream);
            ossClient.shutdown();
            String url = "http://" + bucketName + "." + endpoint + "/" + fileName;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}

2、控制层

@Api(tags="阿里云文件管理")
@CrossOrigin 	//跨域
@RestController
@RequestMapping("/eduoss/fileoss")
public class OssController {

    @Autowired
    private OssService ossService;

    //上传头像
    @ApiOperation(value = "文件上传")
    @PostMapping("/upload")
    public R uploadOssFile(@RequestParam("file") MultipartFile file){
        //返回上传到oss的路径
        String url = ossService.uploadFileAvatar(file);

        return R.ok().data("url",url).message("文件上传成功");
    }
}

4、测试 - http://localhost:8002/swagger-ui.html


http://www.kaotop.com/file/tupian/20220516/Snipaste_2022-05-08_23-01-03.png


5、优化文件上传

多次上传相同的名称文件会导致最后一次上传把之前的文件覆盖

把文件名称拼接 uuid,让每个文件名不同并将文件进行按日期分类管理
public String uploadFileAvatar(MultipartFile file) {

    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
    String datePath = new DateTime().toString("yyyy/MM/dd");
    
    InputStream inputStream = null;
    try {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 获取上传文件的输入流
        inputStream = file.getInputStream();
        //获取文件名称
        String fileName = file.getOriginalFilename();
        fileName = datePath + "/" + uuid + fileName;
        //调用oss实例中的方法实现上传
        ossClient.putObject(bucketName, fileName, inputStream);
        ossClient.shutdown();
        
        return "http://" + bucketName + "." + endpoint + "/" + fileName;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}


二、Nginx配置反向代理

这里直接用 Window版本的(资料里有)

将 9001 端口 根据正则表达式匹配对应的端口 8001、8002

1、 nginx.conf 添加

server {
	listen       9001;
    server_name  localhost;
	
    location ~ /eduservice/ {
		proxy_pass http://localhost:8001;
    }
       
    location ~ /eduoss/ {
		proxy_pass http://localhost:8002;
    }
}

2、修改前端端口号 - config/dev.env.js

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  BASE_API: '"http://localhost:9001"',
})

三、上传讲师头像

1、将资料的上传组件复制到 src/components

2、使用组件 save.vue


<el-form-item label="讲师头像">
  
  <pan-thumb :image="teacher.avatar" />
  
  <el-button type="primary" icon="el-icon-upload" @click="imagecropperShow = true">更换头像el-button>
  
  <image-cropper v-show="imagecropperShow" :width="300" :height="300" 
				 :key="imagecropperKey" 
				 :url="BASE_API + '/eduoss/fileoss/upload'" 
				 field="file" 
				 @close="close" @crop-upload-success="cropSuccess" />
el-form-item>
//引入头像组件
import ImageCropper from '@/components/ImageCropper'
import PanThumb from '@/components/PanThumb'

export default {
  components: { ImageCropper, PanThumb },
  data() {
    return {
    	...
      imagecropperShow: false,
      imagecropperKey: 0,
      BASE_API: process.env.BASE_API,
    };
  },	
  methods: {
    // 关闭上传d框的方法
    close() {
      this.imagecropperShow = false;
      //上传组件初始化 id+1
      this.imagecropperKey = this.imagecropperKey + 1
    },
    // 文件上传
    cropSuccess(data) { //上传成功的方法
      this.imagecropperShow = false;
      //参数resp.data被封装到了方法参数data中了
      this.teacher.avatar = data.url
      this.imagecropperKey = this.imagecropperKey + 1
    },
  }
}

上传成功后:图片地址

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/926400.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)

保存