使用阿里云OSS上传文件到云端的基本用法

目的:希望在前端上传的头像图片存入云端,然后返回该图片的url给前端更新用户的头像信息

前端: 如何把文件对象传给后端?

1.在表单里编写fileInput

<form @submit.prevent="upload_photo">
  <input id="fileInput" type="file" name="file" />
   <button type="submit">上传</button>
</form>

2.写一个请求后端的ajax函数

const upload_photo = () => {

            // 1.获得文件的input标签
            const fileInput = document.getElementById('fileInput');
 
            // 2.获得文件的对象
            const file = fileInput.files[0];
            console.log(file)
            if (!file) {
                error_message.value = "请选择一个文件";
                return;
            }

            // 3.将文件对象转化为可以传输的formData
            const formData = new FormData();
            formData.append('file', file);
            console.log(formData)
            // 4,传文件给后端
            $.ajax({
                url: "http://127.0.0.1:9090/user/account/upload",
                type: "post",
                data: formData,
                processData: false, // 必须禁用JQuery处理数据
                contentType: false, // 必须禁用JQuery设置content-type
                headers: {
                    Authorization: "Bearer " + store.state.user.token,
                },
                success(resp) {
                    console.log(resp);
                    error_message.value = "";
                    if (resp.error_message === "success") {
                        photo.value = resp.path;
                    } else {
                        error_message.value = resp.error_message;
                    }
                }, error() {
                    // console.log(resp);
                }
            });
        };

后端

1.使用阿里云免费试用3个月的OSS

在这里插入图片描述

2.创建UpLoadUtil类

package com.edu.mju.backend.config.utils;

import com.aliyun.oss.*;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

// 上传文件的工具类

public class UpLoadUtil {
    //1.OSS 域名
   public static final String ALI_DOMAIN = ""

   public static Map<String,String> uploadRemote(MultipartFile file) throws IOException {
       Map<String,String> resp = new HashMap<>();

       // 2.生成文件名
       String originalFileName = file.getOriginalFilename();
       // ext:.和该文件扩展名
       String ext = "." + FilenameUtils.getExtension(originalFileName);

       // 将 -变成 "'
       String uuid = UUID.randomUUID().toString().replace("-", "");
       String fileName = uuid + ext;
       // 3.地域节点
       String endPoint = ""
       // 4.oss的两个key 
       String accessKeyID = "";
       String accessKeySecret ="";
       // 4.OSS客户端对象

       OSS ossClient = new OSSClientBuilder().build(endPoint,accessKeyID,accessKeySecret);
       // putObject(仓库名,文件名,文件.getInputStream)
       ossClient.putObject(仓库名,文件名,文件.getInputStream);
       ossClient.shutdown(); // 关闭阿里云 oss仓库

       resp.put("path",ALI_DOMAIN + fileName);
       resp.put("error_message","success");
       return resp;
   }
}

3.controller层

   @PostMapping("/user/account/upload")
    public Map<String,String> upload(@RequestParam("file") MultipartFile file) throws IOException {
        String contentType = file.getContentType();
        Map<String,String> res = new HashMap<>();

        // 只支持JPG和PNG格式
        if (!contentType.equals("image/jpeg") && !contentType.equals("image/png")) {
            res.put("error_message","只允许上传 JPG 或 PNG 格式的图片文件");
            return res;
        }
        // 文件上传到云端
        return UpLoadUtil.uploadRemote(file);
        // 调用上传到本地 return updateService.uploadPhoto(file);
    }

4.service层

@Override
    public Map<String, String> uploadPhoto(MultipartFile file) {
        Map<String,String> resp = new HashMap<>();

        if(file.isEmpty()){
            resp.put("error_message","上传图片不能为空!");
            return resp;
        }
        // 更改图片名防止重命名
        String originalFileName = file.getOriginalFilename();
        // .和,之后的部分
        String ext = "." + originalFileName.split("\\.")[1];  // 1.png 取 .png
        String uuid = UUID.randomUUID().toString().replace("-", "");

        // 新文件名 = 随机生成的前缀 + 原来的后缀
        String newFileName = uuid + ext;

        // 得到路径的前缀
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());

        String pre = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() +"\\src\\main\\resources\\static\\images\\";
        System.out.println(pre);
        // 最后的路径 = 前缀 + 文件名
        String path = pre + newFileName;
        try {
            file.transferTo(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        resp.put("error_message","success");
        resp.put("path",path);
        return resp;
    }
  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值