java 上传文件到oss(阿里云)

做这个功能之前我们需要导入阿里云OSS官方提供的工具包
aliyun-sdk-oss-2.5.0.jar 这个文件 如果有最新版的话就下载最新版

aliyun.upload.AliyunConfig

package aliyun.upload;

public final class AliyunConfig 
{
    //你的oss所在域,要加http://   不明白可以对照你的文件引用地址
    public static String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";

    //密匙keyId 可以在阿里云获取到
    public static String accessKeyId = "xxxxxxx";

    //密匙keySecret 可以在阿里云获取到
    public static String accessKeySecret = "";

    //你的bucketName 名称   即是你的OSS对象名称  不明白查oss开发文档专业术语 
    public static String bucketName = "";
}

aliyun.upload.IAliyunUpload

package aliyun.upload;

public interface IAliyunUpload 
{
    /**
     * @param
     * String filePathName 本地图片路径(D:/xxxx/xxxx....../xx/xx.jgp|xx.png|..)
     * String savePathName 将要保存到OSS上的路径地址
     * */
    public String uploadFile(String filePathName,String savePathName);
}

aliyun.upload.AliyunUploadVersion1

package aliyun.upload;

import java.io.File;
import java.io.IOException;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CompleteMultipartUploadResult;
import com.aliyun.oss.model.UploadFileRequest;
import com.aliyun.oss.model.UploadFileResult;

import Log.Log;

/**
 * 阿里云文件上传 - 简易版
 * */
public class AliyunUploadVersion1 implements IAliyunUpload
{

    /**
     * 断点续传
     * */
    @Override
    public String uploadFile(String uploadFile,String savePathName)
    {
        OSSClient ossClient = new OSSClient(AliyunConfig.endpoint, AliyunConfig.accessKeyId, AliyunConfig.accessKeySecret);

        try {
            UploadFileRequest uploadFileRequest = new UploadFileRequest(AliyunConfig.bucketName,savePathName);
            // 待上传的本地文件
            uploadFileRequest.setUploadFile(uploadFile);

            // 设置并发下载数,默认1
            uploadFileRequest.setTaskNum(5);
            // 设置分片大小,默认100KB
            uploadFileRequest.setPartSize(1024 * 1024 * 1);
            // 开启断点续传,默认关闭
            uploadFileRequest.setEnableCheckpoint(true);

            UploadFileResult uploadResult = ossClient.uploadFile(uploadFileRequest);

            CompleteMultipartUploadResult multipartUploadResult = 
                    uploadResult.getMultipartUploadResult();
            return multipartUploadResult.getLocation();
        } catch (OSSException oe) {

            Log.e("*************************************************OSS upload file error  create_date " + tool.Tool.getDate() + "*************************************");

            Log.e("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            Log.e("Error Message: " + oe.getErrorCode());
            Log.e("Error Code:       " + oe.getErrorCode());
            Log.e("Request ID:      " + oe.getRequestId());
            Log.e("Host ID:           " + oe.getHostId());
            Log.e("*************************************************OSS upload file error*************************************");
        } catch (ClientException ce) {
            Log.e("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            Log.e("Error Message: " + ce.getMessage());
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }

        return null;
    }
}

文件上传容器

package aliyun.upload;

import org.springframework.stereotype.Repository;

@Repository("aliyun_upload")
public class AliyunUpload extends AliyunUploadVersion1
{

    /**
     * 上传文件
     * */
    @Override
    public String uploadFile(String filePath,String savePathName)
    {
        return super.uploadFile(filePath,savePathName);
    }

}   

spring.beans.service.UploadService 文件上传服务

package spring.beans.service;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import aliyun.upload.AliyunUpload;
import tool.RandomNumStr;
import tool.Tool;

@Service(value="upload_service")
public class UploadService 
{
    //默认 本地存储路径
    private final String save_local_path = "D:/java_class/Company/WebRoot/";

    //默认  文件保存路径
    private String save_context_path = "Upload/images/";

    public void setSavePath(String savePath)
    {
        this.save_context_path = savePath;
    }

    /**
     * 阿里云文件上传
     * @param
     * MultipartFile file 文件流
     * @return
     * String 文件引用路径 如 String filePath = "http://aliyun.xxxx.xxxx/xxxx/xxxx/xxxx.jpg"
     * */
    public String aliyunUploadFile(MultipartFile file)
    {
        //获取文件名称
        String fileName = file.getOriginalFilename();

        //生成存储路径
        String save_handler_path = save_local_path + save_context_path;

        //获得文件后缀
        String prefix=fileName.substring(fileName.lastIndexOf("."));

        //存储目录
        File parentDir = new File(save_handler_path);

        //存储目录是否存在
        if(!parentDir.exists())
        {
            parentDir.mkdirs();
        }

        //生成文件存储名称
        String fileSaveName = RandomNumStr.createRandomString(7) + String.valueOf(new Date().getTime()) + prefix;

        try{
            File saveFile = new File(save_handler_path,fileSaveName);
            //移动临时文件
            file.transferTo(saveFile);

            //新增阿里云文件上传
            AliyunUpload aliyunUpload = new AliyunUpload();

            String fileUrl = aliyunUpload.uploadFile(save_handler_path+fileSaveName,save_context_path+fileSaveName);

            saveFile.delete();

            return fileUrl;
        }catch(IOException e)
        {
            return null;
        }
    }

    /**
     * 文件存储
     * @param
     * MyltipartFile file 文件资源
     * @return
     * 文件文件存储地址
     * */
    public String localUploadFile(MultipartFile file,HttpServletRequest request)
    {
        //获取文件名称
        String fileName = file.getOriginalFilename();

        //生成存储路径
        String save_handler_path = save_local_path + save_context_path;

        //获得文件后缀
        String prefix=fileName.substring(fileName.lastIndexOf("."));

        //存储目录
        File parentDir = new File(save_handler_path);

        //存储目录是否存在
        if(!parentDir.exists())
        {
            parentDir.mkdirs();
        }

        //生成文件存储名称
        String fileSaveName = RandomNumStr.createRandomString(7) + String.valueOf(new Date().getTime()) + prefix;

        try{
            //移动临时文件
            file.transferTo(new File(save_handler_path,fileSaveName));

            //文件地址
            return Tool.getDomain(request) + save_context_path + fileSaveName;
        }catch(IOException e)
        {
            return null;
        }
    }
}
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值