阿里OSS对象存储,实现图片上传代码;

一.注册阿里云账号,购买OSS服务

获取 : 连接区域地址endpoint ;需要存储的bucketName;图片保存路径picLocation ;连接keyId;accessKeyId ;连接秘钥accessKeySecret;

(一).在配置文件config.properties中配置阿里云文件:

            #oss文件储存配置
            #连接区域地址
            endpoint=
            #需要存储的bucketName
            bucketName=
            #图片保存路径
            picLocation=
            #连接keyId
            accessKeyId=
            #连接秘钥
            accessKeySecret=

( 二 ).编写工具类

============================================================================
1.读取config.properties配置文件类

package com.tc.common.pic;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**

  • 读取后缀名为“.properties”的文件

  • @author

    */

public class SystemConfig

{

private static final String CONFIG_PROPERTIES = "conf/config.properties";

public static String getConfigResource(String key) throws IOException

{

    ClassLoader loader = Thread.currentThread().getContextClassLoader();

    Properties properties = new Properties();

    InputStream in = loader.getResourceAsStream(CONFIG_PROPERTIES);

    properties.load(in);

    String value = properties.getProperty(key);

    // 编码转换,从ISO-8859-1转向指定编码  

    value = new String(value.getBytes("ISO-8859-1"), "UTF-8");

    in.close();

    return value;

}

}

============================================================================
2.获取config.properties配置文件中的配置数据
package com.tc.common.pic;

/**

  • Project Name:

  • FileName: PageController

  • Author: zq

  • Date: 2018/5/2

  • @since: 1.0.0

    */

import java.io.IOException;

/**

  • @ClassName: OSSConfig

  • @Description: OSS配置类

  • @author AggerChen

  • 2016年11月4日 下午3:58:36

    */

public class OSSConfig

{

private String endpoint;       //连接区域地址

private String accessKeyId;    //连接keyId

private String accessKeySecret;    //连接秘钥

private String bucketName;     //需要存储的bucketName

private String picLocation;    //图片保存路径

public OSSConfig()

{

    try

    {

        this.endpoint = SystemConfig.getConfigResource("endpoint");

        this.bucketName = SystemConfig.getConfigResource("bucketName");

        this.picLocation = SystemConfig.getConfigResource("picLocation");

        this.accessKeyId = SystemConfig.getConfigResource("accessKeyId");

        this.accessKeySecret = SystemConfig

                .getConfigResource("accessKeySecret");

    }

    catch (IOException e)

    {

        e.printStackTrace();

    }

}

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 getPicLocation()

{

    return picLocation;

}

public void setPicLocation(String picLocation)

{

    this.picLocation = picLocation;

}

}

============================================================================
3.获取OSS上传图片的核心工具类

package com.tc.common.pic;

/**

  • FileName: PageController

  • Author: zq

  • Date: 2018/5/2

  • @since: 1.0.0

    */

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStream;

import java.util.ArrayList;

import java.util.List;

import java.util.UUID;

import com.aliyun.oss.ClientException;

import com.aliyun.oss.OSSClient;

import com.aliyun.oss.OSSException;

import com.aliyun.oss.model.DeleteObjectsRequest;

import com.aliyun.oss.model.DeleteObjectsResult;

import com.aliyun.oss.model.GenericRequest;

import com.aliyun.oss.model.ObjectMetadata;

import com.aliyun.oss.model.PutObjectRequest;

import org.springframework.web.multipart.commons.CommonsMultipartFile;

/**

*

  • @ClassName: OSSUploadUtil

  • @Description: 阿里云OSS文件上传工具类

  • @author AggerChen

  • 2016年11月3日 下午12:03:24

    */

public class OSSUploadUtil

{

private static OSSConfig config = null;

/**

 * @MethodName: uploadFile

 * @Description: OSS单文件上传

 * @param file

 * @param fileType 文件后缀

 * @return String 文件地址

 */

public static String uploadFile(CommonsMultipartFile file, String fileType)

{

    config = config == null ? new OSSConfig() : config;

    String fileName = config.getPicLocation() + UUID.randomUUID().toString()

            .toUpperCase().replace("-", "") + "." + fileType; //文件名,根据UUID来

    return putObject(file, fileType, fileName);

}



/**

 * @MethodName: updateFile

 * @Description: 更新文件:只更新内容,不更新文件名和文件地址。

 *      (因为地址没变,可能存在浏览器原数据缓存,不能及时加载新数据,例如图片更新,请注意)

 * @param file

 * @param fileType

 * @param oldUrl

 * @return String

 */

public static String updateFile(CommonsMultipartFile file, String fileType,

        String oldUrl)

{

    String fileName = getFileName(oldUrl);

    if (fileName == null)

        return null;

    return putObject(file, fileType, fileName);

}

/**

 * @MethodName: replaceFile

 * @Description: 替换文件:删除原文件并上传新文件,文件名和地址同时替换

 *     解决原数据缓存问题,只要更新了地址,就能重新加载数据)

 * @param file

 * @param fileType 文件后缀

 * @param oldUrl 需要删除的文件地址

 * @return String 文件地址

 */

public static String replaceFile(CommonsMultipartFile file, String fileType,

        String oldUrl)

{

    boolean flag = deleteFile(oldUrl);      //先删除原文件

    if (!flag)

    {

        //更改文件的过期时间,让他到期自动删除。

    }

    return uploadFile(file, fileType);

}



/**

 *

 * @MethodName: deleteFile

 * @Description: 单文件删除

 * @param fileUrl 需要删除的文件url

 * @return boolean 是否删除成功

 */

public static boolean deleteFile(String fileUrl)

{

    config = config == null ? new OSSConfig() : config;

    String bucketName = OSSUploadUtil

            .getBucketName(fileUrl);       //根据url获取bucketName

    String fileName = OSSUploadUtil

            .getFileName(fileUrl);           //根据url获取fileName

    if (bucketName == null || fileName == null)

        return false;

    OSSClient ossClient = null;

    try

    {

        ossClient = new OSSClient(config.getEndpoint(),

                config.getAccessKeyId(), config.getAccessKeySecret());

        GenericRequest request = new DeleteObjectsRequest(bucketName)

                .withKey(fileName);

        ossClient.deleteObject(request);

    }

    catch (Exception oe)

    {

        oe.printStackTrace();

        return false;

    }

    finally

    {

        ossClient.shutdown();

    }

    return true;

}



/**

 * @MethodName: batchDeleteFiles

 * @Description: 批量文件删除(较快):适用于相同endPoint和BucketName

 * @param fileUrls 需要删除的文件url集合

 * @return int 成功删除的个数

 */

public static int deleteFile(List<String> fileUrls)

{

    int deleteCount = 0;    //成功删除的个数

    String bucketName = OSSUploadUtil

            .getBucketName(fileUrls.get(0));       //根据url获取bucketName

    List<String> fileNames = OSSUploadUtil

            .getFileName(fileUrls);         //根据url获取fileName

    if (bucketName == null || fileNames.size() <= 0)

        return 0;

    OSSClient ossClient = null;

    try

    {

        ossClient = new OSSClient(config.getEndpoint(),

                config.getAccessKeyId(), config.getAccessKeySecret());

        DeleteObjectsRequest request = new DeleteObjectsRequest(bucketName)

                .withKeys(fileNames);

        DeleteObjectsResult result = ossClient.deleteObjects(request);

        deleteCount = result.getDeletedObjects().size();

    }

    catch (OSSException oe)

    {

        oe.printStackTrace();

        throw new RuntimeException("OSS服务异常:", oe);

    }

    catch (ClientException ce)

    {

        ce.printStackTrace();

        throw new RuntimeException("OSS客户端异常:", ce);

    }

    finally

    {

        ossClient.shutdown();

    }

    return deleteCount;

}





/**

 * @MethodName: batchDeleteFiles

 * @Description: 批量文件删除(较慢):适用于不同endPoint和BucketName

 * @param fileUrls 需要删除的文件url集合

 * @return int 成功删除的个数

 */

public static int deleteFiles(List<String> fileUrls)

{

    int count = 0;

    for (String url : fileUrls)

    {

        if (deleteFile(url))

        {

            count++;

        }

    }

    return count;

}



/**

 *

 * @MethodName: putObject

 * @Description: 上传文件

 * @param file

 * @param fileType

 * @param fileName

 * @return String

 */

private static String putObject(CommonsMultipartFile file, String fileType,

        String fileName)

{

    config = config == null ? new OSSConfig() : config;

    String url = null;      //默认null

    OSSClient ossClient = null;

    try

    {

        ossClient = new OSSClient(config.getEndpoint(),

        config.getAccessKeyId(), config.getAccessKeySecret());

        InputStream input = file.getInputStream();

        ObjectMetadata meta = new ObjectMetadata();             // 创建上传Object的Metadata

        meta.setContentType(

                OSSUploadUtil.contentType(fileType));       // 设置上传内容类型

        meta.setCacheControl("no-cache");                   // 被下载时网页的缓存行为

        PutObjectRequest request = new PutObjectRequest(

                config.getBucketName(), fileName, input,

                meta);           //创建上传请求

        ossClient.putObject(request);

        url = config.getEndpoint().replaceFirst("http://",

                "http://" + config.getBucketName() + ".") + "/"

                + fileName;       //上传成功再返回的文件路径

    }

    catch (OSSException oe)

    {

        oe.printStackTrace();

        return null;

    }

    catch (ClientException ce)

    {

        ce.printStackTrace();

        return null;

    }

    catch (FileNotFoundException e)

    {

        e.printStackTrace();

        return null;

    }

    catch (IOException e)

    {

        e.printStackTrace();

    }

    finally

    {

        ossClient.shutdown();

    }

    return url;

}



/**

 * @MethodName: contentType

 * @Description: 获取文件类型

 * @param fileType

 * @return String

 */

private static String contentType(String fileType)

{

    fileType = fileType.toLowerCase();

    String contentType = "";

    if (fileType.equals("bmp"))

    {

        contentType = "image/bmp";

    }

    else if (fileType.equals("gif"))

    {

        contentType = "image/gif";

    }

    else if (fileType.equals("png") || fileType.equals("jpeg") || fileType

            .equals("jpg"))

    {

        contentType = "image/jpeg";

    }

    else if (fileType.equals("html"))

    {

        contentType = "text/html";

    }

    else if (fileType.equals("txt"))

    {

        contentType = "text/plain";

    }

    else if (fileType.equals("vsd"))

    {

        contentType = "application/vnd.visio";

    }

    else if (fileType.equals("ppt") || fileType.equals("pptx"))

    {

        contentType = "application/vnd.ms-powerpoint";

    }

    else if (fileType.equals("doc") || fileType.equals("docx"))

    {

        contentType = "application/msword";

    }

    else if (fileType.equals("xml"))

    {

        contentType = "text/xml";

    }

    else if (fileType.equals("mp4"))

    {

        contentType = "video/mp4";

    }

    else

    {

        contentType = "application/octet-stream";

    }

    return contentType;

}



/**

 *

 * @MethodName: getBucketName

 * @Description: 根据url获取bucketName

 * @param fileUrl 文件url

 * @return String bucketName

 */

private static String getBucketName(String fileUrl)

{

    String http = "http://";

    String https = "https://";

    int httpIndex = fileUrl.indexOf(http);

    int httpsIndex = fileUrl.indexOf(https);

    int startIndex = 0;

    if (httpIndex == -1)

    {

        if (httpsIndex == -1)

        {

            return null;

        }

        else

        {

            startIndex = httpsIndex + https.length();

        }

    }

    else

    {

        startIndex = httpIndex + http.length();

    }

    int endIndex = fileUrl.indexOf(".oss-");

    return fileUrl.substring(startIndex, endIndex);

}



/**

 * @MethodName: getFileName

 * @Description: 根据url获取fileName

 * @param fileUrl 文件url

 * @return String fileName

 */

private static String getFileName(String fileUrl)

{

    String str = "aliyuncs.com/";

    int beginIndex = fileUrl.indexOf(str);

    if (beginIndex == -1)

        return null;

    return fileUrl.substring(beginIndex + str.length());

}



/**

 *

 * @MethodName: getFileName

 * @Description: 根据url获取fileNames集合

 * @param fileUrls 文件url

 * @return List<String>  fileName集合

 */

private static List<String> getFileName(List<String> fileUrls)

{

    List<String> names = new ArrayList<String>();

    for (String url : fileUrls)

    {

        names.add(getFileName(url));

    }

    return names;

}

}

============================================================================

4.后台controller中调用工具类实现图片上传

package com.tc.lvmsm.controller.gm;

import com.tc.common.bean.cm.CmService;

import com.tc.common.log.BaseController;

import com.tc.common.log.ModuleLogger;

import com.tc.common.log.ModuleLoggerFactory;

import com.tc.common.page.Page;

import com.tc.common.pic.OSSUploadUtil;

import com.tc.lvmsm.serv.itf.GasCylinderCheckInfoService;

import com.tc.lvmsm.serv.itf.GasService;

import com.tc.lvmsm.vo.cm.VehicleAndGasCylinderAndGasCylinderCheckInfo;

import com.tc.lvmsm.vo.gm.*;

import com.tc.lvmsm.vo.vm.Vehicle;

import com.tc.lvmsm.vo.vm.VehicleExample;

import com.tc.util.DateUtils;

import com.tc.util.ExcelUtil;

import org.apache.shiro.SecurityUtils;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.*;

import java.net.URLDecoder;

import java.net.URLEncoder;

import java.util.*;

/**

  • FileName: GasCylinderCheckInfoController

  • Author: 苏凯

  • Date: 2018/3/22 19:08

  • @version 1.0.0

  • @since: 1.0.0

    */

@Controller

public class GasCylinderCheckInfoController

{

/**

 * 配置管理、Service层各模块接口bean

 */

@Autowired

private CmService cmServiceFactory;

/**

 * 气瓶管理、气瓶定检service

 */

@Autowired

private GasCylinderCheckInfoService gasCylinderCheckInfoService;

/**

 * 配置管理 气瓶service

 */

@Autowired

private GasService gasService;

/**

 * 获得日志句柄

 */

private ModuleLogger logger = ModuleLoggerFactory

        .getDefinedLogger("GM\\GasCylinderCheckInfoController ");



/*
 * ========================上传oss============================================
 */


/**

 * 文件上传

 */

@RequestMapping(value = “/config/create-AllGasCylinderCheckInfoFileurlFileUpload”, method = RequestMethod.POST)

@ResponseBody

public Page AllGasCylinderCheckInfoProductqualifyurlFileUpload(

        @RequestParam("file") List<CommonsMultipartFile> files,

        HttpServletRequest request) throws IOException

{

    String CALLER = "GasCylinderCheckInfoController_/config/create-AllGasCylinderCheckInfoFileurlFileUpload ";

    String startTime = DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss");

    String fileName = "";

    String fileType = "";

    Page page = new Page();

    String urls = "";

    try

    {

        if (null != files && 0 < files.size())

        {

            for (int i = 0; i < files.size(); i++)

            {

                if (!files.get(i).isEmpty())

                {

                    // 文件保存路径

                    CommonsMultipartFile file = (CommonsMultipartFile) files

                            .get(i);

                    fileName = file.getOriginalFilename();

                    if (null != fileName && 0 < fileName.length())

                    {

                        fileType = fileName

                                .substring(fileName.lastIndexOf(".") + 1);

                    }

                      //图片上传调用阿里OSS工具OSSUploadUtil接口

                    String url = OSSUploadUtil.uploadFile(file, fileType);



                   if (null != url && 0 < url.length())

                    {

                        urls += url + ",";

                    }

                    else

                    {

                        page.setFailDesc("图片上传不成功!");

                        page.setResultCode(505);

                    }

                }

            }

            if (null != urls && 0 < urls.length())

            {

                page.setFieldString(urls);

                page.setFailDesc("图片上传成功!");

                page.setResultCode(200);

            }

        }

        else

        {

            page.setFailDesc("未获取到文件信息!");

            page.setResultCode(505);

        }

    }

    catch (Exception e)

    {

        e.printStackTrace();

        BaseController.saveLog(

                SecurityUtils.getSubject().getPrincipals().toString(),

                startTime, DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss"),

                BaseController.getRequestIp(request), "气瓶信息", "气瓶定检信息",

                "增加气瓶定检信息/文件上传", 0, 1, "系统异常文件上传失败!" + CALLER);

    }

    finally

    {

        return page;

    }

}

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值