0
点赞
收藏
分享

微信扫一扫

Java文件上传至ECS、OSS、项目路径下

12a597c01003 2022-04-30 阅读 75

OSS依赖

        <!--oss依赖-->
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.10.2</version>
        </dependency>

代码工具类

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@Slf4j
@Component
public class UploadFileUtils {
  /**
     * 上传图片到oss
     * @param multipartFile
     * @param fileCatalog
     * @return
     */
    public static String uploadFileToOSS(MultipartFile multipartFile, String fileCatalog) {
        //地域节点
        String endpoint = "xxxxxxxxx.com";// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        //AccessKey管理
        String accessKeyId = "xxxxxxxxxxxxxx";
        String accessKeySecret = "xxxxxxxxxxx";
        //bucket名称
        String bucketName = "xxxxxx-oss";
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            //获取文件流
            InputStream inputStream=multipartFile.getInputStream();
            //构建日期文件
            SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy/MM/dd");
            String datePath=dateFormat.format(new Date());
            //获取到文件名
            String originName= multipartFile.getOriginalFilename();
            //文件名
            String fileName = UUID.randomUUID().toString();
            //后缀
            String suffix=originName.substring(originName.lastIndexOf("."));
            //新文件名
            String newName=fileName+suffix;
            //完整路径
            String fileUrl="xxxxx"+fileCatalog+datePath+"/"+newName;
            //文件上传到阿里云服务器
            ossClient.putObject(bucketName,fileUrl,inputStream);
            //返回路径
            String filePath="https://"+bucketName+"."+endpoint+"/"+fileUrl;
            //编写日志
            log.info("文件已上传:"+filePath);
            return filePath;

        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        } finally {
            //关闭ossClient
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
    /**
     * 上传图片到云服务器
     * @param multipartFile
     * @param fileCatalog
     * @return
     */
    public static String uploadFileToECS(MultipartFile multipartFile, String fileCatalog) {
        //构建日期文件
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyMMdd");
        String datePath=dateFormat.format(new Date());
        //获取到文件名
        String originName= multipartFile.getOriginalFilename();
        //文件名
        String fileName = UUID.randomUUID().toString();
        //后缀
        String suffix=originName.substring(originName.lastIndexOf("."));
        //新文件名
        String newName=datePath+fileName+suffix;
        //保存文件的绝对路径
        try {
            String path = "/www/tomcat/uploadfile";
            String url="https://主机号:端口号/uploadfile";
            File folder=new File(path+fileCatalog);
            if (!folder.isDirectory()) {
                folder.mkdirs();
            }
            multipartFile.transferTo(new File(folder+"/"+newName));
            //图片路径
            String filePath = url+fileCatalog+newName;
            return filePath;
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 上传图片到项目路径下
     */
    public static String uploadFileToPS(MultipartFile multipartFile, String fileCatalog,HttpServletRequest req) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        // 上传的文件将保存在项目运行目录下的 uploadFile 文件夹,
        String realPath = req.getSession().getServletContext().getRealPath(fileCatalog);//工程目录创建
        // 并且在 uploadFile 文件夹中通过日期对上传的文件归类保存
        String format = sdf.format(new Date());
        File folder = new File(realPath + format);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        // 对上传的文件重命名,避免文件重名
        String oldName = multipartFile.getOriginalFilename();
        String newName = UUID.randomUUID().toString()
                + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            // 文件保存
            multipartFile.transferTo(new File(folder, newName));

            // 返回上传文件的访问路径
            String filePath = req.getScheme() + "://" + req.getServerName()
                    + ":"+ "/file"+fileCatalog+ format + newName;
            //编写日志
            log.info("文件已上传:"+filePath);

            return filePath;

        } catch (IOException e) {
            e.printStackTrace();

        }
        return null;
    }
}

举报

相关推荐

0 条评论