上传图片至七牛云

本文总阅读量
本文最后更新于2 分钟前,文中所描述的信息可能已发生改变。

使用的方式为服务端上传

导入七牛云JAVA-SDK

java
<dependency>  
    <groupId>com.qiniu</groupId>  
    <artifactId>qiniu-java-sdk</artifactId>  
    <version>[7.13.0, 7.13.99]</version>
</dependency>

前端上传组件

使用element-plusel-load进行发送请求给后端文件上传接口,点击立即上传

  • axios部分
js
import axios from 'axios'
import {getToken} from '@/api/token.js'
const api = axios.create({
    baseURL: "http://localhost:8081",
    timeout: 5*1000,
    // headers: {'Content-Type': 'application/json;charset=utf-8'}
})
api.interceptors.request.use(request=>{
    if(getToken()){
        request.headers['Authorization'] = getToken()
    }
    return request
},error=>{
    Promise.reject(error)
})

api.interceptors.response.use(response=>{
    console.log("响应值")
    console.log(response.data)
    return response.data
},error=>{
    Promise.reject(error)
})

export default api
  • axios请求
js
import api from '@/api/request.js'
export function fileLoad(file){
    return api({
        url: '/api/test/file/load',
        method: 'POST',
        data:file
    })
}
  • html部分
html
<template>
  <el-upload 
  ref="uploadRef" 
  action="#" 
  list-type="picture-card" 
  :limit="1"
  :http-request="handleUpload"
  :before-upload="handleChange"
  accept=".png,.jpe,.jpeg"
  >
    <el-icon><Plus /></el-icon>

    <template #file="{ file }">
      <div>
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
        <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
          >
            <el-icon><zoom-in /></el-icon>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleDownload(file)"
          >
            <el-icon><Download /></el-icon>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file)"
          >
            <el-icon><Delete /></el-icon>
          </span>
        </span>
      </div>
    </template>
  </el-upload>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
  <el-button class="ml-3" type="success" @click="submitUpload">
      upload to server
    </el-button>
</template>
  • js部分
js
<script setup>
import { ref } from 'vue'
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
import {fileLoad} from '@/api/file.js'

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)

const uploadRef = ref()

const handleRemove = (file) => {
  console.log(file)
}

const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

const handleDownload = (file) => {
  console.log(file)
}

const submitUpload = () => {
  let fd = new FormData()
  fd.append("image",uploadRef.value)
  console.log(uploadRef.value)
  console.log(fd)
}

const handleChange = (rawFile) => {
  if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
    ElMessage.error("只能上传jpeg/jpg/png图片");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 20) {
    ElMessage.error("上传图片最大不超过1MB!");
    return false;
  }
  return true;
}

const handleUpload = async (file) => {
  let fd = new FormData();
  //变为表单对象
  fd.append("image", file.file);
    fileLoad(fd).then(res=>{
      console.log("上传成功")
        console.log(res)
    }).catch(err=>{
        console.log(err)
    })

}
</script>

后端接口

复制七牛云java-sdk文档中的服务端上传部分的代码稍作修改即可 Tips: ==文件链接为你绑定的域名+上传方法返回的key==

  • 上传方法
java
@Component
public class QiNiuUtils {
    @Autowired
    private QiNiuProperties qn;
    @LogRecord(module = "文件服务",operation = "文件上传")
    public String upload(MultipartFile file,String fileName){
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        //...其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证,然后准备上传


        //默认不指定key的情况下,以文件内容的hash值作为文件名

        try {
            byte[] uploadBytes = file.getBytes();
            Auth auth = Auth.create(qn.getAccessKey(), qn.getSecretKey());
            String upToken = auth.uploadToken(qn.getBucket());
            try {
                Response response = uploadManager.put(uploadBytes, fileName, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = JsonUtil.convert(response.bodyString(), DefaultPutRet.class);

                System.out.println("putRet.key: "+putRet.key);
                System.out.println("putRet.hash: "+putRet.hash);
                //返回的key即是上传后文件在容器中的文件名
                return putRet.key;
            } catch (QiniuException ex) {
                ex.printStackTrace();
                if (ex.response != null) {
                    System.err.println(ex.response);

                    try {
                        String body = ex.response.toString();
                        System.err.println(body);
                    } catch (Exception ignored) {
                    }
                }
            }
        } catch (IOException ex) {
            //ignore
        }

        return null;

    }
}
  • QiNiuProperties资源类
java
@ConfigurationProperties("qi-niu")
@Component
@Data
public class QiNiuProperties {
    /**
     * 七牛云控制台中复制
     */
    public String accessKey;
    public String secretKey;
    /**
     * 创建的桶名称
     */
    public String bucket;
}
  • yml中配置相应属性
yml
qi-niu:  
accessKey: **********
secretKey: **********
bucket: holo-blog
  • 测试接口

如果==要放入桶中的images文件夹下==,将其作为文件名前缀即可,七牛云会自动识别

java
@PostMapping("/file/load")
    public Result fileLoad(@RequestParam("image") MultipartFile file){
        //源文件名
        String filename = file.getOriginalFilename();
        System.out.println("filename = " + filename);
        // 如果要方入桶中的images文件夹下,将其作为文件名前缀即可,七牛云会自动识别
        filename = "images/"+UUID.randomUUID() +filename;
        System.out.println("filename = " + filename);
        String fileUrl = qn.upload(file, filename);
        return fileUrl!=null? Result.success(fileUrl,"上传成功"):Result.fail(StatusCode.FAIL.value(), "上传失败");
    }

Tips:前端发送表单数据中的数据项中文件的属性名要和后端接口中接收参数指定的文件属性名相同

参考文章

vue3使用ElementPlus upload上传文件的两种方式

Netty简单使用
SpringBoot当中使用自定义注解结合AOP做权限校验
Valaxy v0.18.5 驱动 | 主题 - Yun v0.18.5
本站总访问量
本站访客数 人次
本站已运行0 天0 小时0 分0 秒后缀