阿里云OSS图片上传

上传工具类
package com.common.uitls;

import java.util.Iterator;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

public class OSSUtils {

	public static String accessKeyId = "**************";//阿里云API的密钥Access Key ID
	public static String accessKeySecret = "****************";//阿里云API的密钥Access Key Secret
	public static String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";//阿里云API的外网域名 
	public static String ossEndPoint="http://bucket.img-cn-shenzhen.aliyuncs.com";//
	public static String bucketName = "bucket"; //阿里云API的bucket名称 


	/*
	 * 上传图片到阿里云服务器Object
	 */
	public static boolean putObjectFile(String key,InputStream content,long fLength) {
		boolean isIMG = true;
		// 初始化OSSClient
		OSSClient client = new OSSClient(ossEndPoint,accessKeyId, accessKeySecret);
		try{
			
			String[] hz = key.split("\\.");
			String hz_ = hz[1];
			if(hz_.equals("jpg")||hz_.equals("jpeg")||hz_.equals("png")||hz_.equals("bmp")){
				ossEndPoint = "http://img-cn-shenzhen.aliyuncs.com";
			}else{
				isIMG = false;
				ossEndPoint = "http://oss-cn-shenzhen.aliyuncs.com";
			}
			
			// 创建上传Object的Metadata
			ObjectMetadata meta = new ObjectMetadata();
			// 必须设置ContentLength
			meta.setContentLength(fLength);
			//	   meta.setContentType("text/plain");
			// 上传Object.
			PutObjectResult result = client.putObject(bucketName, key, content, meta);
		}catch(Exception ex){
			return false;
		}finally {
			if(content!=null){
				try {
					content.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(client != null){
				client.shutdown();
			}
			return true;
		}
	}


	/*
	 * 上传图片到阿里云服务器Object   不鉴黄
	 */
	public static boolean putObjectFile2(String key,InputStream content,long fLength) {
		try{
			ossEndPoint = "http://bucket.img-cn-shenzhen.aliyuncs.com";
			// 初始化OSSClient
			OSSClient client = new OSSClient(endpoint,accessKeyId, accessKeySecret);
			// 创建上传Object的Metadata
			ObjectMetadata meta = new ObjectMetadata();
			// 必须设置ContentLength
			meta.setContentLength(fLength);
			//	   meta.setContentType("text/plain");
			// 上传Object.
			PutObjectResult result = client.putObject(bucketName, key, content, meta);
		}catch(Exception ex){
			return false;
		}
		return true;

	}
	
	/**
	 * @Description: 读取OSS上面文件的内容
	 * @param @param filePath
	 * @param @param filename
	 * @param @return  
	 * @return String[]    
	 */
	public static String[] readTxtFile(String filename) {
		   String[] keyBuffer = new String[15000];// endpoint "http://bucket.oss-cn-shenzhen.aliyuncs.com/*****";
		   OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);  
		    try {
		    	    String bucketName = "wlsqbucket";                      
			        OSSObject ossObject = ossClient.getObject(bucketName, "file/smarthome/remotecontrol/AC/"+filename+".txt");  
			        // 读Object内容  
			        System.out.println("Object content:");  
			        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent())); 
			        String lineTxt;
		            int cnt = 0;
		            while ((lineTxt = bufferedReader.readLine()) != null) {
		                keyBuffer[cnt] = lineTxt;
		                cnt++;
		            }
		           // reader.close();  
			        // 关闭client  
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				 ossClient.shutdown();
			}
		    return keyBuffer;
	}
	
	
	public static String[] readTxtFile(String filename) {
		   String[] keyBuffer = new String[15000];// endpoint "http://bucket.oss-cn-shenzhen.aliyuncs.com/**/**/"
		   OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);  
		    try {
		    	    String bucketName = "wlsqbucket";                    
			        OSSObject ossObject = ossClient.getObject(new GetObjectRequest(bucketName, "**/**/**/AC/"+filename+".txt"));   // bucketName, "file/smarthome/remotecontrol/AC/1.txt"
			        // 读Object内容  
			        System.out.println("Object content:");  
			        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent())); 
			        String lineTxt;
		            int cnt = 0;
		            while ((lineTxt = bufferedReader.readLine()) != null) {
		                keyBuffer[cnt] = lineTxt;
		                cnt++;
		            }
		           // reader.close();  
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				// 关闭client  
				 ossClient.shutdown();
			}
		    return keyBuffer;
	}

	//单个图片上传
	@RequestMapping(value = "/uplodFinishAlrm", produces = "text/plain;charset=utf-8", method = RequestMethod.POST)
	@ResponseBody
	public String uplodFinishAlrm(HttpServletRequest request){
		try{
			System.out.println("<!-------------------uplodFinishAlrm-------------");
			
			CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
			if (resolver.isMultipart(request)) {
				// 上传图片
				MultipartHttpServletRequest mrequest = (MultipartHttpServletRequest) request;
				Iterator<String> it = mrequest.getFileNames();
				MultipartFile file = null;

				if (it.hasNext()) {
					file = mrequest.getFile(it.next());
				}

				if (file != null) {
					//home/linkage_alarm_photo 阿里云图片上传地址
					String filename = "home/linkage_alarm_photo/", originalName = file.getOriginalFilename();
					String[] o = originalName.split("_");
					
					System.out.println.info("---------originalName={}",originalName);
					
					String msg_id = o[0];

					filename = filename + o[0] + "/" + originalName;

					InputStream content = file.getInputStream();
					boolean up_result = putObjectFile(filename, content, file.getBytes().length);

					if (up_result) {
						//业务操作
						return "";
					}else{
						return "上传失败";
					}
				}
			} else {
				// 没有图片
				return "没有可上传图片";
			}
		}catch(Exception e){
			System.out.println.error("---uplodFinishAlrm,error={}"+"上传图片异常");
			return "系统异常";
		}
		return "上传成功";
	}
	
	
	/*
	 * 上传图片到阿里云服务器Object
	 */
	public static boolean putObjectFile(String key,InputStream content,long fLength) {
		boolean isIMG = true;
		// 初始化OSSClient
		OSSClient client = new OSSClient(ossEndPoint,accessKeyId, accessKeySecret);
		try{
			
			String[] hz = key.split("\\.");
			String hz_ = hz[1];
			if(hz_.equals("jpg")||hz_.equals("jpeg")||hz_.equals("png")||hz_.equals("bmp")){
				ossEndPoint = "http://img-cn-shenzhen.aliyuncs.com";
			}else{
				isIMG = false;
				ossEndPoint = "http://oss-cn-shenzhen.aliyuncs.com";
			}
			
			// 创建上传Object的Metadata
			ObjectMetadata meta = new ObjectMetadata();
			// 必须设置ContentLength
			meta.setContentLength(fLength);
			//	   meta.setContentType("text/plain");
			// 上传Object.
			PutObjectResult result = client.putObject(bucketName, key, content, meta);
		}catch(Exception ex){
			return false;
		}finally {
			if(content!=null){
				try {
					content.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(client != null){
				client.shutdown();
			}
			return true;
		}
	}
	
		/*
	 * 上传图片到阿里云服务器Object   不鉴黄
	 */
	public static boolean putObjectFile2(String key,InputStream content,long fLength) {
		try{
			ossEndPoint = "http://wlsqbucket.img-cn-shenzhen.aliyuncs.com";
			// 初始化OSSClient
			OSSClient client = new OSSClient(endpoint,accessKeyId, accessKeySecret);
			// 创建上传Object的Metadata
			ObjectMetadata meta = new ObjectMetadata();
			// 必须设置ContentLength
			meta.setContentLength(fLength);
			//	   meta.setContentType("text/plain");
			// 上传Object.
			PutObjectResult result = client.putObject(bucketName, key, content, meta);
		}catch(Exception ex){
			return false;
		}
		return true;
	}
	
	 /** 
     * 创建文件夹 
     * @param ossClient oss连接 
     * @param bucketName 存储空间 
     * @param folder   文件夹名如 
     * @return  文件夹名 
     */  
    public  static String createFolder(OSSClient ossClient,String bucketName,String folder){  
    	GatewayDeviceLog.info("-----------------设备上传图片folder={}",folder);
        //文件夹名   
        final String keySuffixWithSlash =folder;  
        //判断文件夹是否存在,不存在则创建  
        if(!ossClient.doesObjectExist(bucketName, keySuffixWithSlash)){ 
        	GatewayDeviceLog.info("-------创建文件夹");
            //创建文件夹  
            ossClient.putObject(bucketName, keySuffixWithSlash, new ByteArrayInputStream(new byte[0]));  
//            logger.info("创建文件夹成功");  
            //得到文件夹名  
            OSSObject object = ossClient.getObject(bucketName, keySuffixWithSlash);  
            String fileDir=object.getKey(); 
            GatewayDeviceLog.info("-----------创建成功fileDir={}"+fileDir);
            return fileDir;  
        }  
        return keySuffixWithSlash;  
    }  

	public static void main(String[] args) {
		readTxtFile("1");	
	}            

具体操作业务实现示例

<form id="submit_form" method="post" action="image/upload_image" target="exec_target" enctype="multipart/form-data">
	<div class="uploadBtnPri "><input class="uploadBtnPri " style="opacity:0;" type="file" name="file" id="upload_file"></div>
	<div class="uploadBtnPri uploadBtnColor" style="">请上传图片</div>
</form>

$("#submit_form").submit();



1、jsp页面上传
/**
 * 上传图片
 * @param file
 * @return
 */
@RequestMapping("image/upload_image")
@ResponseBody
public String uploadShopImg(@RequestParam("file") MultipartFile file){
	String url = "";
	logger.info("===========================image/upload_image=============================");
	if(file==null){
		logger.info("=======file is empty");
	}
	   try{
			url = OSSUtils.uploadFile("阿里云OSS图片存储文件路径", file);
			logger.info("url={}",url);
	   }
	   catch (final Exception e) {
			e.printStackTrace();
	   }
   return url;
}

2、接口上传
@RequestMapping(value = "/uplodFinishAlrm", produces = "text/plain;charset=utf-8", method = RequestMethod.POST)
@ResponseBody
public ServerResponse uplodFinishAlrm(HttpServletRequest request){
	try{
		CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		if (resolver.isMultipart(request)) {
			// 上传图片
			MultipartHttpServletRequest mrequest = (MultipartHttpServletRequest) request;
			Iterator<String> it = mrequest.getFileNames();
			MultipartFile file = null;

			if (it.hasNext()) {
				file = mrequest.getFile(it.next());
			}

			if (file != null) {
				String filename = "阿里云OSS图片存储文件路径", originalName = file.getOriginalFilename();

				filename = filename + "/" + originalName;

				InputStream content = file.getInputStream();
								
				boolean up_result = OSSUtils.putObjectFile(filename, content, file.getBytes().length);

				if (up_result) {
					System.out.println("上传成功");
				}else{
					System.out.println("上传失败");
				}
			}
		} else {
			// 没有图片
			System.out.println("没有可上传图片");
		}
	}catch(Exception e){
		e.printStackTrace();
	}
	return null;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值