使用阿里云OSS 实现图片上传(前端layui)

第一步: 导入oss依赖

          
			com.aliyun.oss
			aliyun-sdk-oss
			2.8.3
		

 前端HTML:

 
    

前端js:

layui.use('upload', function(){
        var $ = layui.jquery
            ,upload = layui.upload;

        var uploadInst = upload.render({
               
            // 上传图片的按钮id
            elem: '#importCounterImg'
            ,url: xxxx
            ,accept:'images'
            ,size:50000
            ,before: function(obj){
                obj.preview(function(index, file, result){
                    // 上传成功加载图片
                    $('#demo1').attr('src', result);
                });
            }
            ,done: function(res){
                //如果上传失败
                if(res.code > 0){
                    return layer.msg('上传失败');
                }
                //上传成功
                var demoText = $('#demoText');
                demoText.html('上传成功');

                 // 将上传返回的路径值添加到相对应的参数上
                var fileupload = $("#counterImg");
                fileupload.attr("value",res.data.src);
            }
            ,error: function(){
                //演示失败状态,并实现重传
                var demoText = $('#demoText');
                demoText.html('上传失败 重试');
                demoText.find('.demo-reload').on('click', function(){
                    uploadInst.upload();
                });
            }
        });

 

后端controller部分代码:

//图片上传
    @ResponseBody
    @RequestMapping("upload")
    public Map upload(MultipartFile file, HttpServletRequest request) throws Exception{

        String endpoint = "xx";
        String accessKeyId = "xx";
        String accessKeySecret = "xx";
        String bucketName = "xx";
        String default_expire_time = 31536000000L

        String prefix="";
        String dateStr="";
        //保存上传
        OutputStream out = null;
        InputStream fileInput=null;
        try{
            if(file!=null){
                String originalName = file.getOriginalFilename();
                prefix=originalName.substring(originalName.lastIndexOf(".")+1);
                Date date = new Date();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                dateStr = simpleDateFormat.format(date);
                String filepath = "D:\\down\\images\\" + dateStr+"\\"+originalName+"." + prefix;
                  // 先上传到本地
                File files=new File(filepath);
                if(!files.getParentFile().exists()){
                    files.getParentFile().mkdirs();
                }
                file.transferTo(files);

                DefaultOSSClient client = new DefaultOSSClient(endpoint, accessKeyId, accessKeySecret, bucketName);
                String objectKey = "store/" + System.currentTimeMillis();
                InputStream inputStream = new FileInputStream(new File(filepath));
                URL url = client.simpleUpload(objectKey, inputStream, OssMimeType.JPG, true, client.default_expire_time);

                Map map2=new HashMap<>();
                Map map=new HashMap<>();
                map.put("code",0);
                map.put("msg","");
                map.put("data",map2);
                map2.put("src",url);
                return map;
            }

        }catch (Exception e){
        }finally{
            try {
                if(out!=null){
                    out.close();
                }
                if(fileInput!=null){
                    fileInput.close();
                }
            } catch (IOException e) {
            }
        }
        Map map=new HashMap<>();
        map.put("code",1);
        map.put("msg","");
        return map;
    }

 

工具类OssUtil :

package cn.com.jala.retailer.manage.util;

import cn.com.jala.retailer.manage.oss.DefaultOSSClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author dzm
 * @date 2019/4/3
 */
@Component
public  class OssUtil {

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

    private DefaultOSSClient defaultOSSClient;

    public DefaultOSSClient getOSSClient() {
        if(defaultOSSClient == null) {
            this.defaultOSSClient = new DefaultOSSClient(endpoint, accessKeyId, accessKeySecret, bucketName);
        }
        return defaultOSSClient;
    }

}

工具类:》DefaultOSSClient 

package cn.com.xx.manage.oss;


import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

/**
 * @author dzm
 * @date 2019/4/3
 */
@Data
@Slf4j
public class DefaultOSSClient {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;
    public   long default_expire_time = 31536000000L;

    public DefaultOSSClient(String endpoint, String accessKeyId, String accessKeySecret, String bucketName) {
        this.endpoint = endpoint;
        this.accessKeyId = accessKeyId;
        this.accessKeySecret = accessKeySecret;
        this.bucketName = bucketName;
        OSSClient ossClient = new OSSClient(this.endpoint, this.accessKeyId, this.accessKeySecret);
        try {
            if (!ossClient.doesBucketExist(bucketName)) {
                throw new OSSException("您的Bucket " + bucketName +"不存在");
            }
            BucketInfo info = ossClient.getBucketInfo(bucketName);
            System.out.println("Bucket " + bucketName + "的信息如下:");
            System.out.println("\t数据中心:" + info.getBucket().getLocation());
            System.out.println("\t创建时间:" + info.getBucket().getCreationDate());
            System.out.println("\t用户标志:" + info.getBucket().getOwner());
        } catch (Exception e) {
            throw new OssClientException(e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public URL generatePresignedUrl(String objectKey) {
        return generatePresignedUrl(objectKey, default_expire_time);
    }

    public URL generatePresignedUrl(String objectKey, long expireTimeMillis) {
        OSSClient ossClient = new OSSClient(this.endpoint, this.accessKeyId, this.accessKeySecret);
        try {
            // 生成以GET方法访问的签名URL,访客可以直接通过浏览器访问相关内容。
            return generatePresignedUrl(ossClient, objectKey, expireTimeMillis);
        } catch (Exception e) {
            throw new OssClientException(e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    private URL generatePresignedUrl(OSSClient ossClient, String objectKey, long expireTimeMillis) {
        URL url = ossClient.generatePresignedUrl(this.bucketName, objectKey, new Date(System.currentTimeMillis() + expireTimeMillis));
        String host = url.getHost();
        if(host.indexOf("-internal.aliyuncs.com") >= 0) {
            host = host.replace("-internal.aliyuncs.com", ".aliyuncs.com");
            try {
                url = new URL(url.getProtocol(), host, url.getPort(), url.getFile());
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        }
        return url;
    }

    /**
     * 简单文件上传
     * @param objectKey
     * @param inputStream
     * @param mimeType
     * @param isGenerateUrl
     * @return
     */
    public URL simpleUpload(String objectKey, InputStream inputStream, OssMimeType mimeType, boolean isGenerateUrl) {
        return simpleUpload(objectKey, inputStream, mimeType, isGenerateUrl, default_expire_time);
    }

    public URL simpleUpload(String objectKey, InputStream inputStream, OssMimeType mimeType, boolean isGenerateUrl, long expireTimeMillis) {
        OSSClient ossClient = new OSSClient(this.endpoint, this.accessKeyId, this.accessKeySecret);
        try {
            PutObjectRequest request = new PutObjectRequest(this.bucketName, objectKey, inputStream);
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(mimeType.getContentType());
            request.setMetadata(metadata);
            PutObjectResult result = ossClient.putObject(request);
//            ossClient.putObject(this.bucketName, objectKey, inputStream);
            if(isGenerateUrl) {
                // 生成以GET方法访问的签名URL,访客可以直接通过浏览器访问相关内容。
                return generatePresignedUrl(ossClient, objectKey, expireTimeMillis);
            }
            return null;
        } catch (Exception e) {
            throw new OssClientException(e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public URL simpleUpload(String objectKey, InputStream inputStream, boolean isGenerateUrl) {
        return simpleUpload(objectKey, inputStream, isGenerateUrl, default_expire_time);
    }

    public URL simpleUpload(String objectKey, InputStream inputStream, boolean isGenerateUrl, long expireTimeMillis) {
        OSSClient ossClient = new OSSClient(this.endpoint, this.accessKeyId, this.accessKeySecret);
        try {
            ossClient.putObject(this.bucketName, objectKey, inputStream);
            if(isGenerateUrl) {
                // 生成以GET方法访问的签名URL,访客可以直接通过浏览器访问相关内容。
                return generatePresignedUrl(ossClient, objectKey, expireTimeMillis);
            }
            return null;
        } catch (Exception e) {
            throw new OssClientException(e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 上传本地文件
     * @param objectKey
     * @param file
     */
    public URL simpleUpload(String objectKey, File file, OssMimeType mimeType, boolean isGenerateUrl) {
        return simpleUpload(objectKey, file, mimeType, isGenerateUrl, default_expire_time);
    }

    public URL simpleUpload(String objectKey, File file, OssMimeType mimeType, boolean isGenerateUrl, long expireTimeMillis) {
        OSSClient ossClient = new OSSClient(this.endpoint, this.accessKeyId, this.accessKeySecret);
        try {
            PutObjectRequest request = new PutObjectRequest(this.bucketName, objectKey, file);
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(mimeType.getContentType());
            request.setMetadata(metadata);
            ossClient.putObject(request);
            if(isGenerateUrl) {
                return generatePresignedUrl(ossClient, objectKey, expireTimeMillis);
            }
            return null;
        } catch (Exception e) {
            throw new OssClientException(e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public URL simpleUpload(String objectKey, File file, boolean isGenerateUrl) {
        return simpleUpload(objectKey, file, isGenerateUrl, default_expire_time);
    }

    public URL simpleUpload(String objectKey, File file, boolean isGenerateUrl, long expireTimeMillis) {
        OSSClient ossClient = new OSSClient(this.endpoint, this.accessKeyId, this.accessKeySecret);
        try {
            ossClient.putObject(this.bucketName, objectKey, file);
            if(isGenerateUrl) {
                return generatePresignedUrl(ossClient, objectKey, expireTimeMillis);
            }
            return null;
        } catch (Exception e) {
            throw new OssClientException(e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 断点续传上传。
     * @param objectKey  上传的文件名
     * @param localFilePath  待上传文件的本地路径
     */
    public URL breakpointUpload(String objectKey, String localFilePath, OssMimeType mimeType, boolean isGenerateUrl) throws Throwable {
        return this.breakpointUpload(objectKey, localFilePath, mimeType, isGenerateUrl, 5, 1 * 1024 * 1024);
    }

    /**
     * 断点续传上传。
     * @param objectKey 上传的文件名
     * @param localFilePath 待上传文件的本地路径
     * @param taskNum 上传并发线程数
     * @param partSize 上传的分片大小,范围为100KB~5GB,默认大小为 1024*100=100K
     * @throws Throwable
     */
    public URL breakpointUpload(String objectKey, String localFilePath, OssMimeType mimeType, boolean isGenerateUrl, int taskNum, long partSize) throws Throwable {
        OSSClient ossClient = new OSSClient(this.endpoint, this.accessKeyId, this.accessKeySecret);
        try {
            ObjectMetadata meta = new ObjectMetadata();
            // 指定上传的内容类型。
            meta.setContentType(mimeType.getContentType());

            // 通过UploadFileRequest设置多个参数。
            UploadFileRequest uploadFileRequest = new UploadFileRequest(this.bucketName, objectKey);

            // 指定上传的本地文件。
            uploadFileRequest.setUploadFile(localFilePath);
            // 指定上传并发线程数,默认为1。
            uploadFileRequest.setTaskNum(taskNum);
            // 指定上传的分片大小,范围为100KB~5GB,默认为文件大小 1024 * 100 = 100K
            uploadFileRequest.setPartSize(partSize);
            // 开启断点续传,默认关闭。
            uploadFileRequest.setEnableCheckpoint(true);
            // 记录本地分片上传结果的文件。开启断点续传功能时需要设置此参数,上传过程中的进度信息会保存在该文件中,如果某一分片上传失败,再次上传时会根据文件中记录的点继续上传。上传完成后,该文件会被删除。默认与待上传的本地文件同目录,为uploadFile.ucp。
            //uploadFileRequest.setCheckpointFile("");
            // 文件的元数据。
            uploadFileRequest.setObjectMetadata(meta);
            // 设置上传成功回调,参数为Callback类型。
            //uploadFileRequest.setCallback("");

            // 断点续传上传。
            ossClient.uploadFile(uploadFileRequest);
            if(isGenerateUrl) {
                return generatePresignedUrl(ossClient, objectKey, default_expire_time);
            }
            return null;
        } catch (Exception e) {
            throw new OssClientException(e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }


    /**
     * 读取文件内容
     * @param objectKey
     * @return
     * @throws IOException
     */
    public StringBuilder readContent(String objectKey) throws IOException {
        OSSClient ossClient = new OSSClient(this.endpoint, this.accessKeyId, this.accessKeySecret);
        try {
            OSSObject ossObject = ossClient.getObject(bucketName, objectKey);
            InputStream inputStream = ossObject.getObjectContent();
            StringBuilder objectContent = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            while (true) {
                String line = reader.readLine();
                if (line == null) {
                    break;
                }
                objectContent.append(line);
            }
            inputStream.close();
            return objectContent;
        } catch (Exception e) {
            throw new OssClientException(e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 下载文件到本地
     * @param objectKey 文件名
     * @param localFilePath 文件下载到本地的路径
     */
    public void downloadFile(String objectKey, String localFilePath) {
        OSSClient ossClient = new OSSClient(this.endpoint, this.accessKeyId, this.accessKeySecret);
        try {
            // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖,不存在则新建。
            ossClient.getObject(new GetObjectRequest(this.bucketName, objectKey), new File(localFilePath));
        } catch (Exception e) {
            throw new OssClientException(e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 断点续传下载
     * @param objectKey 文件名
     * @param localFilePath 文件下载到本地的路径
     * @return
     * @throws Throwable
     */
    public ObjectMetadata breakpointDownload(String objectKey, String localFilePath) throws Throwable {
        return this.breakpointDownload(objectKey, localFilePath, 5, 1 * 1024 * 1024);
    }

    /**
     * 断点续传下载
     * @param objectKey 文件名
     * @param localFilePath 文件下载到本地的路径
     * @param taskNum 分片下载的并发数
     * @param partSize 分片大小,取值范围为1B~5GB。默认大小为 1024*100=100K
     * @return
     * @throws Throwable
     */
    public ObjectMetadata breakpointDownload(String objectKey, String localFilePath, int taskNum, long partSize) throws Throwable {
        OSSClient ossClient = new OSSClient(this.endpoint, this.accessKeyId, this.accessKeySecret);
        try {
            // 下载请求,10个任务并发下载,启动断点续传。
            DownloadFileRequest downloadFileRequest = new DownloadFileRequest(this.bucketName, objectKey);
            downloadFileRequest.setDownloadFile(localFilePath);
            downloadFileRequest.setPartSize(partSize);
            downloadFileRequest.setTaskNum(taskNum);
            downloadFileRequest.setEnableCheckpoint(true);
            // 记录本地分片下载结果的文件。开启断点续传功能时需要设置此参数。下载过程中的进度信息会保存在该文件中,如果某一分片下载失败,再次下载时会根据文件中记录的点继续下载。下载完成后,该文件会被删除。
//            downloadFileRequest.setCheckpointFile("");

            // 下载文件。
            DownloadFileResult downloadRes = ossClient.downloadFile(downloadFileRequest);
            // 下载成功时,会返回文件元信息。
            return downloadRes.getObjectMetadata();
        } catch (Exception e) {
            throw new OssClientException(e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 删除对象
     * @param objectKey
     */
    public void deleteObject(String objectKey) {
        OSSClient ossClient = new OSSClient(this.endpoint, this.accessKeyId, this.accessKeySecret);
        try {
            // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖,不存在则新建。
            ossClient.deleteObject(this.bucketName, objectKey);
            log.info("删除 bucketName:" + this.bucketName + ", objectKey:" + objectKey);
        } catch (Exception e) {
            throw new OssClientException(e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public static void main(String[] args) throws Exception{
        String endpoint = "xx";
        String accessKeyId = "xx";
        String accessKeySecret = "xx";
        String bucketName = "xx";

        DefaultOSSClient client = new DefaultOSSClient(endpoint, accessKeyId, accessKeySecret, bucketName);
        String objectKey = "test/" + System.currentTimeMillis();
        InputStream inputStream = new FileInputStream(new File("D:\\down\\images\\2020-05-24\\123.png"));
        URL url = client.simpleUpload(objectKey, inputStream, OssMimeType.JPG, true, client.default_expire_time);

    }

}

工具类:》OssClientException 

package cn.com.xxx.manage.oss;

/**
 * @author dzm
 * @date 2019/4/15
 */
public class OssClientException extends RuntimeException {
    public OssClientException() {
        super();
    }

    public OssClientException(String message) {
        super(message);
    }

    public OssClientException(String message, Throwable cause) {
        super(message, cause);
    }

    public OssClientException(Throwable cause) {
        super(cause);
    }

    protected OssClientException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

 

工具类:》OssMimeType 

package cn.com.xxx.manage.oss;

/**
 * OSS文件类型,详见:https://help.aliyun.com/knowledge_detail/39522.html
 * @author dzm
 * @date 2019/4/15
 */
public enum OssMimeType {

    /**
     * 二进制流,未知的文件类型
     */
    BYTE("application/octet-stream"),

    /**
     * 文件后缀为 .jpeg  .jpg  .jpe
     */
    JPG("image/jpeg"),

    /**
     * 动图格式文件
     */
    GIF("image/gif"),

    HTML("text/html"),

    TXT("text/plain"),

    DOC("application/msword")

    ;

    private String contentType;

    OssMimeType(String contentType) {
        this.contentType = contentType;
    }

    public String getContentType() {
        return contentType;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }
}

 

你可能感兴趣的:(layui图片上传,oss)