阿里OSS服务器工具类代码

涉及到的jar包需要自己下载

package com.unionx.oss;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;




import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class OSSClientUtil {

    protected static final Logger log = LoggerFactory.getLogger(OSSClientUtil.class);

    @Value("${oss.host.endpoint}")
    private String endpoint;
    @Value("${oss.accessKeyId}")
    private String accessKeyId;
    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${oss.bucket}")
    private String bucketName;
    @Value("${oss.host.images}")
    private String host;

    //图片存储目录
    private String imgdir = "APP/";
    //文件存储目录
    private String filedir = "FILE/";

    /**
     *
     * 上传图片
     * @param file
     * @return
     */
    public String uploadImg2Oss(MultipartFile file) {
        /*if (file.getSize() > 1024 * 1024 *20) {
            return "图片太大";//RestResultGenerator.createErrorResult(ResponseEnum.PHOTO_TOO_MAX);
        }*/
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        Random random = new Random();
        String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
        try {
            InputStream inputStream = file.getInputStream();
            this.uploadFile2OSS(inputStream, name);
            return name;//RestResultGenerator.createSuccessResult(name);
        } catch (Exception e) {
            return "上传失败";//RestResultGenerator.createErrorResult(ResponseEnum.PHOTO_UPLOAD);
        }
    }

    /**
     * 上传图片获取fileUrl
     * @param instream
     * @param fileName
     * @return
     */
    public String uploadFile2OSS(InputStream instream, String fileName) {
        String ret = "";
        try {
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(instream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            //上传文件

            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            PutObjectResult putResult = ossClient.putObject(bucketName, imgdir + fileName, instream, objectMetadata);
            ret = putResult.getETag();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (instream != null) {
                    instream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    public static String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
            }
            if (FilenameExtension.equalsIgnoreCase(".gif")) {
                return "image/gif";
            }
            if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                    FilenameExtension.equalsIgnoreCase(".jpg") ||
                    FilenameExtension.equalsIgnoreCase(".png")) {
                return "image/jpeg";
            }
            if (FilenameExtension.equalsIgnoreCase(".html")) {
                return "text/html";
            }
            if (FilenameExtension.equalsIgnoreCase(".txt")) {
                return "text/plain";
            }
            if (FilenameExtension.equalsIgnoreCase(".vsd")) {
                return "application/vnd.visio";
            }
            if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                    FilenameExtension.equalsIgnoreCase(".ppt")) {
                return "application/vnd.ms-powerpoint";
            }
            if (FilenameExtension.equalsIgnoreCase(".docx") ||
                    FilenameExtension.equalsIgnoreCase(".doc")) {
                return "application/msword";
            }
            if (FilenameExtension.equalsIgnoreCase(".xml")) {
                return "text/xml";
            }
            return "image/jpeg";
        }

    /**
     * 获取图片路径
     * @param fileUrl
     * @return
     */
    public String getImgUrl(String fileUrl) {
        if (!StringUtils.isEmpty(fileUrl)) {
                String[] split = fileUrl.split("/");
                String url =  this.getUrl(this.imgdir + split[split.length - 1]);
//                log.info(url);
//                String[] spilt1 = url.split("\\?");
//                return spilt1[0];
                return url;
        }
        return null;
    }

    /**
     * 获得url链接
     *
     * @param key
     * @return
     */
    public String getUrl(String key) {
        // 设置URL过期时间为10年  3600l* 1000*24*365*10
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
        // 生成URL
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        if (url != null) {
            return url.toString();
        }
        return null;
    }


    /**
     * 多图片上传
     * @param fileList
     * @return
     */
    public String checkList(List<MultipartFile> fileList) {
        String  fileUrl = "";
        String  str = "";
        String  photoUrl = "";
        for(int i = 0;i< fileList.size();i++){
            fileUrl = uploadImg2Oss(fileList.get(i));
            str = getImgUrl(fileUrl);
            if(i == 0){
                photoUrl = str;
            }else {
                photoUrl += "," + str;
            }
        }
        return photoUrl.trim();
    }

    /**
     * 单个图片上传
     * @param file
     * @return
     */
    public String checkImage(MultipartFile file){
        String fileUrl = uploadImg2Oss(file);
        //String str = getImgUrl(fileUrl);
        return host+"/"+imgdir+ fileUrl;
    }
    
    /**
     * 文件删除
     * @param keys
     */
    public void deleteFile(String filePath) {
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        String fileName = getFileName(filePath);
        ossClient.deleteObject(bucketName, imgdir+fileName);
        ossClient.shutdown();
    }
    
    /**
     * 
     * Description:获取文件名
     * @param path
     * @return
     * @return String
     * @author name:luyong <br>email: [email protected]
     *
     */
    public static String getFileName(String path){ 
    	String fileName = new File(path).getName(); 
    	//return fileName.substring(0, fileName.indexOf("?"));
    	return fileName;
	}
    
     /**
     * 
     * Description:上传文件
     * @param fileContent
     * @param fileName
     * @return
     * @throws Exception
     * @return String
     * @author name:luyong <br>email: [email protected]
     *
     */
    public String uploadFile(InputStream fileContent,String fileName) throws Exception {  
        //随机名处理  
        fileName = new Date().getTime() + fileName.substring(fileName.lastIndexOf("."));  
        //初始化OSSClient  
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 创建上传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(getcontentType(fileName.substring(fileName.lastIndexOf("."))));  
        objectMetadata.setContentDisposition("inline;filename=" + fileName);  
        // 上传文件  
        ossClient.putObject(bucketName, filedir + fileName, fileContent, objectMetadata);
        // 关闭OSSClient  
        ossClient.shutdown();  
        // 关闭io流  
        fileContent.close();  
        return host +"/"+ filedir + fileName;  
        
    } 
    
     /**
     * 
     * Description:下载文件
     * @param filePath
     * @param request
     * @param response
     * @return void
     * @author name:luyong <br>email: [email protected]
     *
     */
    public void downloadFile(String filePath, HttpServletRequest request, HttpServletResponse response){
        try {
            String fileName=getFileName(filePath);
            String key=fileName;
            // 从阿里云进行下载
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            OSSObject ossObject = ossClient.getObject(bucketName, filedir+key);
            // 已缓冲的方式从字符输入流中读取文本,缓冲各个字符,从而提供字符、数组和行的高效读取
            BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));
            //InputStream inputStream = ossObject.getObjectContent();
            //缓冲文件输出流
            //BufferedOutputStream outputStream=new BufferedOutputStream(response.getOutputStream());
            //通知浏览器以附件形式下载
            // response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
		    // 为防止 文件名出现乱码
			response.setContentType("application/doc");
			final String userAgent = request.getHeader("USER-AGENT");
			fileName="及时用.apk";
			if(StringUtils.contains(userAgent, "MSIE")){//IE浏览器
			    fileName = URLEncoder.encode(fileName,"UTF-8");
			}else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐浏览器
			    fileName = new String(fileName.getBytes(), "ISO8859-1");
			}else{
			    fileName = URLEncoder.encode(fileName,"UTF-8");//其他浏览器
			}
			response.addHeader("Content-Disposition", "attachment;filename=" +fileName);//这里设置一下让浏览器弹出下载提示框,而不是直接在浏览器中打开
			//BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
	        while (true) {
	            String line = reader.readLine();
	            if (line == null) break;
	            //System.out.println("\n" + line);
	        }
	        reader.close();
			/*byte[] car = new byte[1024];
                int read;
                while ((read = inputStream.read(car)) != -1) {
                	outputStream.write(car, 0, read);
                }*/
                /*while((L = inputStream.read(car)) != -1){
                    if (car.length!=0){
                        outputStream.write(car, 0,L);
                    }
                }*/
            /*if(outputStream!=null){
                outputStream.flush();
                outputStream.close();
            }*/
        } catch (IOException e) {
            e.printStackTrace();

        } catch (OSSException e){
        }
    }
    
}


猜你喜欢

转载自blog.csdn.net/weixin_39093006/article/details/88235223