文件传输——本地上传、OSS上传

前端通过upload组件接收数据

action属性,必填项,填写后端接收此文件数据的接口路径

可以额外添加钩子事件::on-success,:on-remove

html 复制代码
            <el-upload 
              class="upload-demo" 
              action="http://localhost:8080/wedu/sys/goods/ImportExcel"
              enctype="multipart/form-data" 
              :headers="tokenInfo">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip">只能上传xlsx文件</div>
            </el-upload>

图片上传,需要设置块来放置复现的图片

html 复制代码
<el-upload
               class="avatar-uploader"
              :action= "uploadUrl"
               :headers= "tokenInfo"
               :show-file-list="false"
               :on-success="handleAvatarSuccess"
               :before-upload="beforeAvatarUpload">
               <img v-if="imageUrl" :src="imageUrl" class="avatar">
               <i v-else class="el-icon-plus avatar-uploader-icon"></i>

             </el-upload>

本地上传

java 复制代码
public R  ImportExcel(@RequestParam("file") MultipartFile file){
        //文件判空
        if (file.isEmpty()) {
            return R.error("文件为空");
        }
        //文件名=当前时间到毫秒+原来的文件名
        String fileName = System.currentTimeMillis() + file.getOriginalFilename();
        //文件路径,歌曲存储路径
        String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "***";
        //如果文件路径不存在,新增该路径
        File file1 = new File(filePath);
        if (!file1.exists()) {
            //创建由此抽象路径名命名的目录。
            file1.mkdir();
        }
        //实际的文件地址
        File dest = new File(filePath + System.getProperty("file.separator") + fileName);
        //可以使用try-catch将此方法包裹
        file.transferTo(dest);
 }

System.getProperty("user.dir"):项目的根目录
System.getProperty("file.separator"):"/",路径分隔符
transferTo():用于将MultipartFile对象中的文件内容写入到指定的文件或目录中,其中包含了关闭文件流的方法

云端上传

阿里云OSS网站

  • 首先引入依赖
xml 复制代码
		<dependency>
			<groupId>com.aliyun.oss</groupId>
			<artifactId>aliyun-sdk-oss</artifactId>
			<version>3.15.1</version>
		</dependency>

如果原框架中有引入,但版本不同,也可以向上通过properties标签中的<aliyun.oss.version>3.15.1</aliyun.oss.version>进行版本修改

  • 设置OSS工具类
java 复制代码
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

//创建bean对象
@Component
public class AliOSSUtils {
    // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
    private String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    // 从环境变量中获取访问凭证。设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
    private String accessKeyId = "个人密钥";
    private String accessKeySecret = "个人密钥";
    // 填写Bucket名称,例如examplebucket。
    private String bucketName = "个人bucket桶";


    /**
     * 实现文件云端上传
     * @param file
     */
    public String upload(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        //起文件名字:当前时间+文件名字
        String fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss"))+file.getOriginalFilename();

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
        ossClient.putObject(bucketName,fileName,inputStream);

        //文件访问路径
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
        ossClient.shutdown();
        return url;
    }
}
  • 前端访问的接口方法
java 复制代码
    //不要忘记装配工具类
	@Autowired
	private AliOSSUtils aliOSSUtils;
	@PostMapping("photoUpload")
	public R photoFile(@RequestParam("file") MultipartFile file){
		try {
		    //直接调用工具类中方法
			String url = aliOSSUtils.upload(file);
			R r = new R();
			r.put("url",url);
			return r;
		} catch (IOException e) {
			return R.error(e.getMessage());

		}
	}
相关推荐
码少女34 分钟前
MySQL--库与表的增删改查基础
java·数据库·mysql
Flynt2 小时前
掘金热文说 Spring Boot 4.1 默认开虚拟线程,我实测后发现了更狠的坑
java·spring boot·性能优化
Resean02233 小时前
Spring 源码分析(一)IOC 容器总览与 refresh() 全景
java·后端·spring
保利威视频SaaS小张3 小时前
企业直播接入笔记 12|企业内训直播怎么做签到和学时统计,防挂机这件事比想象中难
java·前端·数据库·笔记·视频云·polvy·polyv
顧棟5 小时前
【ES实战】 索引模板「可追溯、可校验」:一种模板治理的工程化思路
java·数据库·elasticsearch
玄昌盛不会编程6 小时前
LeetCode——2243. 计算字符串的数字和
java·算法·leetcode
文丑颜不良啊6 小时前
LeetCode3061~3080题目解析
java·leetcode
装不满的克莱因瓶7 小时前
【AI时代必学】一篇文章教会你从零搭建Serverless架构
java·人工智能·ai·云原生·架构·serverless
七夜zippoe8 小时前
多轮对话管理:Session/记忆在 Java 后端怎么存(存储设计实战)
java·开发语言·ai·session·记忆
杨凯凡8 小时前
Spring Boot 事务提交后消息仍会丢?TransactionalEventListener 与 Outbox 可靠投递实战
java·spring boot