阿里云 oss服务器文件上传 java

前天做oss服务器文件上传,之前没了解过,做的过程中遇到许多问题,最终通过查阅相关资料解决了,特分享一下。

首先准备工作 必要的jar 


这里注意版本一致,不然就会报很多坑爹的错误。。

如果你断点调试在执行putObject方法时报错,99%的是jar包有问题。。

然后是配置文件


现在开通oss,都是免费开通的,包年9块钱。

这是几个必要的参数,既然做这个肯定 要知道的!这里就不多做解释了。

这里,首先需要我们创建一个OSS信息实体类,OSSConfigure.Java,用来读取配置文件的信息,封装成实体。

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;  
  /**
   * oss相关参数实体
   * @author liux
   *2017/5/5
   */
public class OSSConfigure {  
  
    private String endpoint;  
    private String accessKeyId;  
    private String accessKeySecret;  
    private String bucketName;  
    private String accessUrl;  
  
    public OSSConfigure() {  
  
    }  
  
    /** 
     * 通过配置文件.properties文件获取,这几项内容。 
     *  
     * @param storageConfName 
     * @throws IOException 
     */  
    public OSSConfigure(String storageConfName) throws IOException {  
  
        Properties prop = new Properties(); 
        InputStream is= super.getClass().getClassLoader().getResourceAsStream(storageConfName);
        prop.load(is);  
  
        endpoint = prop.getProperty("Endpoint").trim();  
        accessKeyId = prop.getProperty("AccessKey").trim();  
        accessKeySecret = prop.getProperty("AccessKeySecret").trim();  
        bucketName = prop.getProperty("BucketName").trim();  
        accessUrl = prop.getProperty("accessUrl").trim();  
  
    }  
  
    public OSSConfigure(String endpoint, String accessKeyId,  
            String accessKeySecret, String bucketName, String accessUrl) {  
  
        this.endpoint = endpoint;  
        this.accessKeyId = accessKeyId;  
        this.accessKeySecret = accessKeySecret;  
        this.bucketName = bucketName;  
        this.accessUrl = accessUrl;  
    }  
  
    public String getEndpoint() {  
        return endpoint;  
    }  
  
    public void setEndpoint(String endpoint) {  
        this.endpoint = endpoint;  
    }  
  
    public String getAccessKeyId() {  
        return accessKeyId;  
    }  
  
    public void setAccessKeyId(String accessKeyId) {  
        this.accessKeyId = accessKeyId;  
    }  
  
    public String getAccessKeySecret() {  
        return accessKeySecret;  
    }  
  
    public void setAccessKeySecret(String accessKeySecret) {  
        this.accessKeySecret = accessKeySecret;  
    }  
  
    public String getBucketName() {  
        return bucketName;  
    }  
  
    public void setBucketName(String bucketName) {  
        this.bucketName = bucketName;  
    }  
  
    public String getAccessUrl() {  
        return accessUrl;  
    }  
  
    public void setAccessUrl(String accessUrl) {  
        this.accessUrl = accessUrl;  
    }  
  
}  


然后就是创建一个OSS文件管理的OSSManageUtil工具类。oss文件存储实际上就是对Object的操作,只要写好路径,都会自动创建的,OSSClient是oss的核心,有兴趣的可以多研究下。我做这个 是要上传app,以及压缩图片后上传,contentType这个方法注意,我上传的是apk  所以要用这个类型application/octet-stream,之前因为这个找了半天错。

package com.cdy.utils;

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


import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;

/**
 * 对OSS服务器进行上传删除等的处理
 * 
 * @ClassName: OSSManageUtil
 * @Description:
 * @author liux
 * @date 2017-5-3 上午10:47:00
 * 
 */
public class OSSManageUtil {
	/**
	 * 上传OSS服务器文件 @Title: uploadFile 
	 *  @param multipartFile spring 上传的文件
	 * remotePath @param oss服务器二级目录
	 *  @throws Exception 设定文件 @return String
	 * 返回类型 @throws
	 */
	public static String uploadFile(InputStream fileContent, String remotePath,String fileName) throws Exception {
		//随机名处理
		fileName = "lxkc_" + new Date().getTime() + fileName.substring(fileName.lastIndexOf("."));
		// 加载配置文件,初始化OSSClient
		OSSConfigure ossConfigure = new OSSConfigure("/system.properties");
		OSSClient ossClient = new OSSClient(ossConfigure.getEndpoint(), ossConfigure.getAccessKeyId(),
				ossConfigure.getAccessKeySecret());
		// 定义二级目录
		String remoteFilePath = remotePath.substring(0, remotePath.length()).replaceAll("\\\\", "/") + "/";
		// 创建上传Object的Metadata
		ObjectMetadata objectMetadata = new ObjectMetadata();
		objectMetadata.setContentLength(fileContent.available());
		objectMetadata.setContentEncoding("utf-8");
		objectMetadata.setCacheControl("no-cache");
		objectMetadata.setHeader("Pragma", "no-cache");
		objectMetadata.setContentType(contentType(fileName.substring(fileName.lastIndexOf("."))));
		objectMetadata.setContentDisposition("inline;filename=" + fileName);
		// 上传文件
		ossClient.putObject(ossConfigure.getBucketName(), remoteFilePath + fileName, fileContent, objectMetadata);
		// 关闭OSSClient
		ossClient.shutdown();
		// 关闭io流
		fileContent.close();
		return ossConfigure.getAccessUrl() + "/" + remoteFilePath + fileName;
	}

	// 下载文件
	@SuppressWarnings("unused")
	public static void downloadFile(OSSConfigure ossConfigure, String key, String filename)
			throws OSSException, ClientException, IOException {
		// 初始化OSSClient
		OSSClient ossClient = new OSSClient(ossConfigure.getEndpoint(), ossConfigure.getAccessKeyId(),
				ossConfigure.getAccessKeySecret());
		OSSObject object = ossClient.getObject(ossConfigure.getBucketName(), key);
		// 获取ObjectMeta
		ObjectMetadata meta = object.getObjectMetadata();

		// 获取Object的输入流
		InputStream objectContent = object.getObjectContent();

		ObjectMetadata objectData = ossClient.getObject(new GetObjectRequest(ossConfigure.getBucketName(), key),
				new File(filename));
		// 关闭数据流
		objectContent.close();

	}

	/**
	 * 根据key删除OSS服务器上的文件 @Title: deleteFile @Description: @param @param
	 * ossConfigure @param @param filePath 设定文件 @return void 返回类型 @throws
	 * @throws IOException 
	 */
	public static void deleteFile( String filePath) throws IOException {
		// 加载配置文件,初始化OSSClient
		OSSConfigure ossConfigure = new OSSConfigure("/system.properties");
		OSSClient ossClient = new OSSClient(ossConfigure.getEndpoint(), ossConfigure.getAccessKeyId(),
				ossConfigure.getAccessKeySecret());
		filePath=filePath.substring(45);
		ossClient.deleteObject(ossConfigure.getBucketName(), filePath);

	}

	/**
	 * Description: 判断OSS服务文件上传时文件的contentType @Version1.0
	 * 
	 * @param FilenameExtension
	 *            文件后缀
	 * @return String
	 */
	public static String contentType(String FilenameExtension) {
		if (FilenameExtension.equals(".BMP") || FilenameExtension.equals(".bmp")) {
			return "image/bmp";
		}
		if (FilenameExtension.equals(".GIF") || FilenameExtension.equals(".gif")) {
			return "image/gif";
		}
		if (FilenameExtension.equals(".JPEG") || FilenameExtension.equals(".jpeg") || FilenameExtension.equals(".JPG")
				|| FilenameExtension.equals(".jpg") || FilenameExtension.equals(".PNG")
				|| FilenameExtension.equals(".png")) {
			return "image/jpeg";
		}
		if (FilenameExtension.equals(".HTML") || FilenameExtension.equals(".html")) {
			return "text/html";
		}
		if (FilenameExtension.equals(".TXT") || FilenameExtension.equals(".txt")) {
			return "text/plain";
		}
		if (FilenameExtension.equals(".VSD") || FilenameExtension.equals(".vsd")) {
			return "application/vnd.visio";
		}
		if (FilenameExtension.equals(".PPTX") || FilenameExtension.equals(".pptx") || FilenameExtension.equals(".PPT")
				|| FilenameExtension.equals(".ppt")) {
			return "application/vnd.ms-powerpoint";
		}
		if (FilenameExtension.equals(".DOCX") || FilenameExtension.equals(".docx") || FilenameExtension.equals(".DOC")
				|| FilenameExtension.equals(".doc")) {
			return "application/msword";
		}
		if (FilenameExtension.equals(".XML") || FilenameExtension.equals(".xml")) {
			return "text/xml";
		}
		if (FilenameExtension.equals(".apk") || FilenameExtension.equals(".APK")) {
			return "application/octet-stream";
		}
		return "text/html";
	}
}

以上是主要代码,再贴一下我的controller,我这里是做的app文件上传


/**
	 * app文件上传
	 *
	 * @param imageFile
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/uploadApp", method = RequestMethod.POST)
	@ResponseBody
	public ImportResponse uploadApp(@RequestParam("app") MultipartFile appFile, VersionUpgrade versionUpgrade) {
		if (versionUpgrade == null) {
			return ImportResponse.fail("上传失败!");
		}
		try {
			 // 流转换 将MultipartFile转换为oss所需的InputStream
 			CommonsMultipartFile cf = (CommonsMultipartFile) appFile;
 			DiskFileItem fi = (DiskFileItem) cf.getFileItem();
 			InputStream fileContent = fi.getInputStream();
 			String fileName = fi.getName();
			String apkUrl = OSSManageUtil.uploadFile( fileContent, "xxapp",fileName);
			versionUpgrade.setApkUrl(apkUrl);
			versionUpgrade.setLoginUserVw(curUser);
			versionUpgradeManager.save(versionUpgrade);
		} catch (Exception e) {
			log.error("【app上传失败】 :", e);
			return ImportResponse.fail("上传失败!");
		}
		return ImportResponse.success("上传成功!");
	}

以上就是全部内容了,都是api里面有的,因为自己做的过程中出现很多问题,所以分享给大家!
 
 

猜你喜欢

转载自blog.csdn.net/java_oss/article/details/71194519