使用阿里雲OSS 實現圖片上傳(前端layui)

第一步: 導入oss依賴

          <dependency>
			<groupId>com.aliyun.oss</groupId>
			<artifactId>aliyun-sdk-oss</artifactId>
			<version>2.8.3</version>
		</dependency>

 前端HTML:

 <!--************這裏是上傳圖片的代碼***************-->
    <div class="layui-form-item">
        <div class="layui-upload">
            <p id="demoText"></p>
            <div class="layui-upload-list" style="width: 50px;height: 100px">
                <img class="layui-upload-img" id="demo1" style="width: auto;height: auto">
            </div>
        </div>
    </div>

前端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('<span style="color: #4cae4c;">上傳成功</span>');

                 // 將上傳返回的路徑值添加到相對應的參數上
                var fileupload = $("#counterImg");
                fileupload.attr("value",res.data.src);
            }
            ,error: function(){
                //演示失敗狀態,並實現重傳
                var demoText = $('#demoText');
                demoText.html('<span style="color: #FF5722;">上傳失敗</span> <a class="layui-btn layui-btn-xs demo-reload">重試</a>');
                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<String,Object> map2=new HashMap<>();
                Map<String,Object> 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<String,Object> 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("<yourCheckpointFile>");
            // 文件的元數據。
            uploadFileRequest.setObjectMetadata(meta);
            // 設置上傳成功回調,參數爲Callback類型。
            //uploadFileRequest.setCallback("<yourCallbackEvent>");

            // 斷點續傳上傳。
            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("<yourCheckpointFile>");

            // 下載文件。
            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 = "http://oss-cn-shanghai.aliyuncs.com";
        String accessKeyId = "LTAI4Fnx9huVib52eTgQ48fn";
        String accessKeySecret = "0ElYxdnzs16TYSssvMkLXwHCZZmTqr";
        String bucketName = "jala-retail";

        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;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章