springboot整合阿里云oss实现单/多文件上传并插入到数据库

工具类

package com.hexu.demo7.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

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

@Slf4j
public class FileNameUtil {
    private static String endpoint = "https://oss-cn-beijing.aliyuncs.com你自己的";
    private static String accessKeyId = "你的accessKeyId";
    private static String accessKeySecret = "你的accessKeySecret";
    private static String bucketName = "你的bucket名称";
    private static String objectKey = "你的目录名称";
    //表示第几张图片   图片入数据库时要用到
    static  int i = 0;
    //根据UUID生成文件名
    public static String getUUIDFileName() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString().replace("-", "");
    }

    //从请求头中提取文件名和类型
    public static String getRealFileName(String context) {
        // Content-Disposition: form-data; name="myfile"; filename="a_left.jpg"
        int index = context.lastIndexOf("=");
        String filename = context.substring(index + 2, context.length() - 1);
        return filename;
    }

    //根据给定的文件名和后缀截取文件名
    public static String getFileType(String fileName) {
        //9527s.jpg
        int index = fileName.lastIndexOf(".");
        return fileName.substring(index);
    }


    //上传文件工具
    public static Map<String, String> stringMap(MultipartFile[] pimage) {
        //定义一个map用于接收图片信息
        HashMap<String, String> objectObjectHashMap = new HashMap<>();
        if (null == pimage) {
            return null;
        }
        //循环遍历
        for ( i = 0; i < pimage.length; i++) {
            MultipartFile multipartFile = pimage[i];
            if (!multipartFile.isEmpty()) {
                //生成文件名
                String file_name = FileNameUtil.getUUIDFileName() + FileNameUtil.getFileType(multipartFile.getOriginalFilename());
                log.info(file_name);
                OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
                try {
                    InputStream multipartFileInputStream = multipartFile.getInputStream();
                    PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,file_name, multipartFileInputStream);
                    ossClient.putObject(putObjectRequest);
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    // 关闭流
                    ossClient.shutdown();
                }
                //放入map集合  这时i的作用就体现出来了
                objectObjectHashMap.put(String.valueOf(i), "路径" + file_name);
            }
        }
        return objectObjectHashMap;
    }

    /**
     * 文件
     * @param fileName
     */
    public static   void filedelete(String fileName){
        log.info(fileName);

       if (null != fileName && "" != fileName) {
           int index = fileName.indexOf("/");
           //根据第一个点的位置 获得第三个点的位置
           index = fileName.indexOf("/", index + 2);
           //根据第三个点的位置,截取 字符串。得到结果 result
           String result = fileName.substring(index + 1);
           OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
           ossClient.deleteObject(bucketName, result);
           ossClient.shutdown();
       }
    }
}

前端配置

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8"/>
  <title>文件上传</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data" action="/providerAll">
  <p>文件1:<input type="file" name="file"/></p>
  <p>文件2:<input type="file" name="file"/></p>
  <p><input type="submit" value="上传" /></p>
</form>
</body>
</html>

后端实现

 /**
     * 文件上传
     * @param provider 接收的实体
     * @param pimage 图片
     * @return
     * @throws IOException
     */
    @PostMapping("/providerAll")
    public String providerAll(SmbmsProvider provider, @RequestParam("file") MultipartFile[] pimage) throws IOException {
    	//这行不用管
        provider.setCreationdate(LocalDateTime.now());
        //这就引用了我们写的工具类   获取map集合里的数据
        Map<String, String> map = FileNameUtil.stringMap(pimage);
        //获取数据并添加到实体类
        provider.setUploadfileerror(map.get("0"));
        provider.setUploadocerror(map.get("1"));
        //添加操作  图片成功添加到数据库
        smbmsProviderService.save(provider);
        return "providerlist";
    }

上一篇:阿里云OSS设置跨域访问


下一篇:这款开发者神器上限究竟有多高?