OSS文件上传组件(小记)

1:定义接收类型

private String[] extention =
        {"doc", "docx", "flv", "mp4", "pdf", "ppt", "pptx", "rar", "txt", "xls", "xlsx", "zip", "default",
               "png","bmp", "jpg", "tiff", "gif", "pcx", "tga", "exif", "fpx", "svg", "psd", "cdr", "pcd", "dxf", "ufo", "eps", "ai", "raw", "jpeg"};

2:上传文件的接口

/**
 * @return
 * @Description 附件上传
 */
@RequestMapping("/upload")
@OperationLog(bizModule = OperationLog.BIZ_ATTACH, operate = "附件上传")
public ResponseJson upload(@RequestParam(value = "file", required = false) MultipartFile file) {
    try {
        boolean flag = false;
        if (file != null && file.getSize() != 0) {
            //大小限制
            if (file.getSize() > 1024 * 1024 * 50) {
                return renderError("大小超过限制");
            } else {
                for (String ext : extention) {
                    //获取后缀
                    String uploadext = FileUtils.getFileExtention(file.getOriginalFilename());
                    if (ext.equals(uploadext)) {
                        flag = true;
                        break;
                    }
                }

                if (flag) {
                    //上传OSS 返回全路径  插入数据库并获取插入后返回的数据
                    Attachment attachment = attachService.doUpload(file, getCurrentUserId(),           getCurrentCorpId(),"oss");
                    return renderSuccess(attachment);
                } else {
                    return renderError("上传类型错误");
                }
            }
        } else {
            return renderError("上传文件不能为空");
        }
    } catch (Exception e) {
        e.printStackTrace();
        return renderError("上传操作失败");
    }
}

3:service调用的doUpload方法

@Autowired
private PathConfig pathConfig;
@Override
@Transactional
public AttachmentPojo doUpload(MultipartFile file, Integer userId, Integer corpId, String from) {
    //上传OSS 返回全路径
    String uploadName = FileUtils.uploadFile(file,pathConfig.getFilepath());
    //插入数据库并获取插入后返回的数据  attachId  name fullFilename type类型
    Attachment attachment = getAttachmentViaMultipartFile(file, userId, corpId, uploadName, from);

    return attachment;
}
/**
 * 插入数据库并获取插入后返回的数据
 */
private Attachment getAttachmentViaMultipartFile(MultipartFile file, int uploadUserId, int uploadUserCorpId, String uploadName, String from) {
    Attachment currentAttachment = new Attachment();
    Map<String, String> map = new HashMap<>();

    long size = file.getSize();

    String originalFilename = FileUtils.getFileNameWithoutExtention(file.getOriginalFilename());
    String uploadTargetFileName = FileUtils.getUploadTargetFileName(file.getOriginalFilename());

    // 全文件名
    String fullFilename = uploadName;
    // 附件扩展名
    String extention = FileUtils.getFileExtention(file.getOriginalFilename());

    currentAttachment.setExtention(extention);
    currentAttachment.setSize((int) (size));
    currentAttachment.setOriginalFilename(originalFilename);
    currentAttachment.setNewFilename(uploadTargetFileName);
    currentAttachment.setFullFilename(fullFilename);
    // 当前创建人
    currentAttachment.setUploadUserId(uploadUserId);
    // crop_id
    currentAttachment.setCorpId(uploadUserCorpId);
    // 判断附件类型 0: 图片\n1:视频\n2:文件
    String type = file.getContentType();
    currentAttachment.setFileType(type);

    //设置hostType="OSS"
    currentAttachment.setHostType(from);

    //插入本地数据库
    insert(currentAttachment);

    return currentAttachment;
}

4:获取配置文件中配置的上传到的服务器位置

package com.XXX.core.config;

import com.XXX.tools.utils.AliUploadUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 路径
 * @author wan
 * @since 
 */
@Configuration
public class PathConfig {
    @Value("${uploadPath.config.filepath}")
    private String filepath;

    public String getFilepath() {
        return  AliUploadUtils.isProdEvn() ? "formal/" +filepath:filepath;
    }
    public void setFilepath(String filepath) { this.filepath = filepath; }

    @Bean
    public PathConfig getPathConfigBean(){
        return  new PathConfig();
    }
}

5:FileUtils工具类

package com.XXX.tools.utils;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * 文 件 名:FileUtils<br/>
 * 文件描述:上传oss时对文件名的处理<br/>
 * 修 改 人: wan <br/>
 * 修改日期:2018年8月14日<br/>
 * 修改内容:<br/>
 */
public class FileUtils {
/**
 * @param file 文件对象
 * @Method: uploadFile(上传)
 */
public static String uploadFile(MultipartFile file, String filepath) {
    try {
        String fileName = file.getOriginalFilename();
        String path = getAliPath(filepath, fileName);
        AliUploadUtils.uploadToAliOss(path, file.getInputStream());
        path = AliUploadUtils.aliOssPath + "/" + path;
        return path;
    } catch (RuntimeException e1) {
        throw e1;
    } catch (Exception e) {
        throw new RuntimeException("文件上传 系统异常");
    }
}
//构造新的文件名(用于上传到服务器)
private static String getAliPath(String filepath, String fileName) {
    String[] fileNames = fileName.split("\\.");
    String name = fileNames[0];
    String suffix = fileNames[fileNames.length - 1].toLowerCase();
    if (name.indexOf(",") >= 0) {
        name = name.replace(",", "");
    }
    String newName = name + UUID.randomUUID() + "." + suffix;
    return filepath + newName;

}
//获取文件前缀的方法
public static String getFileNameWithoutExtention(String fileName) {
    int dotLoc = fileName.lastIndexOf(".");
    //获取附件前缀
    return dotLoc > 0 ? fileName.substring(0, dotLoc) : fileName;
}
//获取文件后缀的方法
public static String getFileExtention(String fileName) {
    int dotLoc = fileName.lastIndexOf(".");
    // 获得附件后缀名称
    return dotLoc > 0 ? fileName.substring(dotLoc + 1) : "";
}
/*
 * 利用文“件名+uuid”来解决上传相同名字的文件的冲突
 */
public static String getUploadTargetFileName(String oldOriginalFileName) {

    String fileNewName = null;
    String originalFileName = null;

    // 开始组装附件名 (利用文件名+uuid来生成文件存储的名字)
    if (StringUtils.isNotEmpty(oldOriginalFileName)) {
        originalFileName = oldOriginalFileName.replace(" ", "");
        // 生成uuid作为附件名称
        String uuid = UUID.randomUUID().toString();

        String extention = getFileNameWithoutExtention(originalFileName);
        return uuid + extention;
    }
    return fileNewName;
}

}

6:阿里云上传工具类

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import org.springframework.core.env.Environment;

import java.io.*;

/**
 * 阿里云上传工具类
 *
 * @author jk
 */
public class AliUploadUtils {
public static final String aliOssPath = "https://XXX.oss-cn-shenzhen.aliyuncs.com";
public static final String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";
private static final String accessKeyId = "your product keyId";
private static final String accessKeySecret = "your product keySecret";
public static final String bucketName = "XXX";
/**
 * 上传文件到阿里云
 *
 * @param inputStream 文件流
 * @param path        上传路径
 * @return
 */
public static Boolean uploadToAliOss(String path, InputStream inputStream) {
    try {
        // endpoint以杭州为例,其它region请按实际情况填写
        String endpoint = AliUploadUtils.endpoint;
        // 云账号AccessKey有所有API访问权限,建议遵循阿里云安全最佳实践,创建并使用RAM子账号进行API访问或日常运维,请登录
        // https://ram.console.aliyun.com 创建
        String accessKeyId = AliUploadUtils.accessKeyId;
        String accessKeySecret = AliUploadUtils.accessKeySecret;
        // 创建OSSClient实例
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 上传文件
        ossClient.putObject(AliUploadUtils.bucketName,path, inputStream);
        // 关闭client
        ossClient.shutdown();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值