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

		}
	}
相关推荐
马里奥Mario2 分钟前
拯救被日志拖垮的线程池:Logback异步化改造实战
java
程序无bug10 分钟前
Spring 当中的Bean 作用域
java
RainbowSea28 分钟前
补充:问题:CORS ,前后端访问跨域问题
java·spring boot·spring
RainbowSea30 分钟前
15. MySQL 多版本并发控制
java·sql·mysql
倔强的石头10638 分钟前
飞算JavaAI:重构软件开发范式的智能引擎
java·数据库·重构
Q_970956391 小时前
java+vue+SpringBoo足球社区管理系统(程序+数据库+报告+部署教程+答辩指导)
java·开发语言·数据库
要开心吖ZSH1 小时前
微服务架构的演进:迈向云原生
java·微服务·云原生
为了更好的明天而战1 小时前
Java 中的 ArrayList 和 LinkedList 区别详解(源码级理解)
java·开发语言
JosieBook2 小时前
【Java编程动手学】Java中的数组与集合
java·开发语言·python
N_NAN_N2 小时前
类图+案例+代码详解:软件设计模式----单例模式
java·单例模式·设计模式