文件传输——本地上传、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());

		}
	}
相关推荐
SL_staff1 小时前
从RBAC到场景化授权:《无忧·企业文档》三级权限模型的技术实践解析
java·开源·产品
传奇开心果编程2 小时前
【springboot基础语法学与练】第 1 课:从零开始
java·spring boot·后端·学习
SL_staff2 小时前
财务系统慎用低代码?从数据模型闭环看合规落地的技术实践
java·低代码·全栈
滕州市燕猫虎计算机科技工作室个体工商户2 小时前
IDEA:Command line is too long
java·ide·intellij-idea
步行cgn2 小时前
Spring p 命名空间注入详解
java·前端·spring
YatHinLay2 小时前
MyBatis 流式查询实战:ResultHandler 处理海量数据
java
天天被压力3 小时前
【跨市场数据实战 #08】可转债折价机会怎么筛:3个接口抓比价、列表和实时盘口
java·人工智能·python
张某布响丸辣3 小时前
附件下载的安全边界:路径白名单、NAS 哨兵文件与 Redis Lua 一次性令牌
java·redis·redis lua·nas哨兵
YatHinLay4 小时前
Spring Boot + Calcite 实现跨库查询
java
酷炫码神4 小时前
MosMos 创意效果与能力边界展示
java