OSS多文件上传

原创
2019/08/09 18:47
阅读数 380

需要的jar包

配置文件

#=============================#
#==== 阿里云 Oss 文件上传设置 ====#
#=============================#

#阿里云EndPoint#
oss.endpoint=
#阿里云BucketName#
oss.bucketName=
#阿里云 文件(图片、文档)上传路径前缀 不设置默认为空#
oss.fileDir=
#阿里云AccessKeyId#
oss.accessKeyId=
#阿里云AccessKeySecret#
oss.accessKeySecret=

OSS工具类

package com.ctrl.aOSS;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.utils.IdGen;
import com.thinkgem.jeesite.common.utils.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author LiPeiMin
 * @Description //TODO
 * @Date 18:21 2019/11/27
 **/
public class aOSS {
    /**
     * 阿里云API的内或外网域名
     */
    private static String endpoint;
    /**
     * 阿里云API的bucket名称
     */
    private static String bucketName;
    /**
     * 阿里云API的文件夹名称
     */
    private static String folder;
    /**
     * 阿里云API的密钥Access Key ID
     */
    private static String accessKeyId;
    /**
     * 阿里云API的密钥Access Key Secret
     */
    private static String accessKeySecret;

    static {
        try {
            endpoint = Global.getConfig("oss.endpoint");
            bucketName = Global.getConfig("oss.bucketName");
            folder = Global.getConfig("oss.fileDir");
            accessKeyId = Global.getConfig("oss.accessKeyId");
            accessKeySecret = Global.getConfig("oss.accessKeySecret");
        } catch (java.lang.Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description TODO //上传图片至OSS
     * @Param [fileContent, ossClient, fileName, bucketName]
     * @Return java.lang.String 返回路径
     * @Author wuyu
     * @Date 18:31 2019/11/27
     */
    public static String uploadFile(MultipartFile file) throws Exception {
        //获取InputStream
        InputStream fileContent = file.getInputStream();
        //最好通过file.getOriginalFilename()   MultipartFile对象获取
        String fileName = file.getOriginalFilename();
        //获取阿里云OSS客户端对象
        OSS ossClients = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //生成文件名称
        fileName = IdGen.uuid() + fileName.substring(fileName.lastIndexOf("."));
        //通过文件名判断并获取OSS服务文件上传时文件的contentType
        String path = getContentType(fileName.substring(fileName.lastIndexOf(".")));
        // 创建上传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(path);
        objectMetadata.setContentDisposition("inline;filename=" + fileName);
        // 上传文件
        //folder+new SimpleDateFormat("YYYYMMdd").format(new Date()) +"/"+ fileName  上传的路径加文件名
        PutObjectResult putResult = ossClients.putObject(bucketName, folder + new SimpleDateFormat("YYYYMMdd").format(new Date()) + "/" + fileName, fileContent, objectMetadata);
        //图片存储再OSS唯一编码
        putResult.getETag();
        // 设置URL过期时间为1小时。
        Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
        // 生成以GET方法访问的签名URL,访客可以直接通过浏览器访问相关内容。
        String url = ossClients.generatePresignedUrl(bucketName, folder + path + "/" + fileName, expiration).toString();
        //截取掉后面的时间参数
        url = StringUtils.substringBefore(url, "?");
        // 关闭OSSClients
        ossClients.shutdown();
        // 关闭io流
        fileContent.close();
        //返回获取到的OSS路径
        return url;
    }

    /**
     * @Description TODO //通过文件名判断并获取OSS服务文件上传时文件的contentType
     * @Param [fileName]文件名
     * @Return java.lang.String 文件的contentType
     * @Author wuyu
     * @Date 18:27 2019/11/27
     */
    public static final String getContentType(String fileName) {
        String FilenameExtension = fileName.substring(fileName.lastIndexOf("."));
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "application/x-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(".xla") ||
                FilenameExtension.equalsIgnoreCase(".xlc") ||
                FilenameExtension.equalsIgnoreCase(".xlm") ||
                FilenameExtension.equalsIgnoreCase(".xls") ||
                FilenameExtension.equalsIgnoreCase(".xlt") ||
                FilenameExtension.equalsIgnoreCase(".xlw")) {
            return "application/vnd.ms-excel";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        if (FilenameExtension.equalsIgnoreCase(".pdf")) {
            return "application/pdf";
        }
        if (FilenameExtension.equalsIgnoreCase(".zip")) {
            return "application/zip";
        }
        if (FilenameExtension.equalsIgnoreCase(".tar")) {
            return "application/x-tar";
        }
        if (FilenameExtension.equalsIgnoreCase(".avi")) {
            return "video/avi";
        }
        if (FilenameExtension.equalsIgnoreCase(".mp4")) {
            return "video/mpeg4";
        }
        if (FilenameExtension.equalsIgnoreCase(".mp3")) {
            return "audio/mp3";
        }
        if (FilenameExtension.equalsIgnoreCase(".mp2")) {
            return "audio/mp2";
        }
        return "application/octet-stream";
    }

}

Controller测试类

package com.ctrl.mobile.ctrlSpController.aOSS;

import com.ctrl.aOSS.aOSS;
import com.ctrl.mobile.respUtils.AppMessage;
import com.ctrl.mobile.respUtils.RespUtils;
import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.web.BaseController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
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.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author LiPeiMin
 * @Description //TODO 文件上传
 * @Date 18:22 2019/11/27
 **/
@Controller
@RequestMapping(value = "/sp/OSS")
public class OSS extends BaseController {
    /**
     * @Description TODO //文件上传
     * @Param [img, response]
     * @Return java.lang.String
     * @Author wuyu
     * @Date 13:44 2019/11/29
     */
    @RequestMapping("getFile")
    public String saveOpinion(@RequestParam("img") MultipartFile img, HttpServletResponse response) {
        Map<String,Object> map = new LinkedHashMap<String, Object>();
        String url = null;
        try {
            url = aOSS.uploadFile(img);
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("url",url);
        RespUtils.getMsgSuccess(map);
        return RespUtils.returnRespJson(response, map);
    }
}

传值部分js

// 实例化
        uploader = WebUploader.create({

            pick: {
            id: '#filePicker',
            label: '点击选择文件'
        },
        dnd: '#uploader .queueList',
        paste: document.body,

        // accept: {
        //     title: 'Images',
        //     extensions: 'gif,jpg,jpeg,bmp,png',
        //     mimeTypes: 'image/gif,image/jpg,image/jpeg,image/bmp,image/png,'
        // },

        // swf文件路径
        swf: 'js/plugins/webuploader/Uploader.swf',
        disableGlobalDnd: true,

        //分页上传
        chunked: true,
        //服务器地址
        server: 'http://localhost:8080/aiyi_platform/f/OSSClient/getFile',   
        //参数名
        fileVal:'img',  //目前用img
        fileNumLimit: 300,
        fileSizeLimit: 200 * 1024 * 1024,    // 200 M
        fileSingleSizeLimit: 50 * 1024 * 1024    // 50 M
        });
//成功回调函数
var imgArr=[];
        //上传成功回调函数
        uploader.on( 'uploadSuccess', function(files,response) {
            var json=JSON.parse(response._raw);  // 使用JSON.parse()进行解析:使用JSON对象的静态方法parse(),将字符串解析为对象。
            imgArr.push(json.respMsg);
            var img = $('<li ><img src="'+imgArr[imgArr.length-1]+'" style="height: 150px;width: 240px"><span id="exit">X</span></li>');
            $("#imgs").append(img );
            $("#url").val(imgArr)
        });
//获取url回显
        var url = $("#url").val();
        if(url!=null && url!=""){
            var urls = url.split(",");
            for (var i = 0; i < urls.length; i++) {
                var href =  urls[i];
                var img = $('<li><img src="'+href+'" style="height: 150px;width: 240px"><span id="exit">X</span></li>');
                imgArr.push(urls[i]);
                $("#imgs").append(img );
            }
        }
//删除 同时删除数组中的路径
        $('#imgs').on('click',' li span',function(){
            var imgArra=$(this).prev().attr('src')
            for(var i=0;i<imgArr.length;i++){
                if(imgArra==imgArr[i]){
                    imgArr.splice(i,1)
                }
            }
            $("#url").val(imgArr);
            $(this).parent().remove();
        })

jsp页面部分代码

<%@ page contentType="text/html;charset=UTF-8" %>
<script src="${ctxStatic}/jquery-fileUpload/js/webuploader.js"></script>
<script src="${ctxStatic}/jquery-fileUpload/js/jquery.sortable.js"></script>
<script src="${ctxStatic}/jquery-fileUpload/js/upload.js"></script>
<link rel="stylesheet" type="text/css" href="${ctxStatic}/jquery-fileUpload/css/webuploader.css" />
<link rel="stylesheet" type="text/css" href="${ctxStatic}/jquery-fileUpload/css/style.css" />
<style>
    #imgs{
        width: 980px;
        height: 192px;
        overflow:auto;
        margin-top: 10px;
    }
    #imgs li{
        display: inline-block;
        position: relative;
        height: 150px;
        width: 240px;
        -webkit-user-select:none;
        -moz-user-select:none;
        -ms-user-select:none;
        user-select:none;
    }
    #imgs li:hover #exit{
        display: block;
    }

    #lefts li{
        /*float: left;*/
        display: inline-block;
    }
    .item_container{
        overflow:auto;
    }
    #exit{
        font-size: 16px;
        text-align: center;
        display: block;
        width: 22px;
        line-height: 22px;
        border-radius: 50%;
        background-color: red;
        color: #ffffff;
        position: absolute;
        top: 5px;
        right: 5px;
        display: none;
        -webkit-user-select:none;
        -moz-user-select:none;
        -ms-user-select:none;
        user-select:none;
    }

    #exit:hover{
        cursor: pointer;
    }
    #exit:active{
        background-color: #ff570a;
        color: #555555;
    }
</style>
<ul id="lefts">
    <li>
        <div class="width_auto" style="width:532px">
            <div id="container">
                <!--头部,相册选择和格式选择-->
                <div id="uploader" >
                    <div class="item_container" style="height: 194px">
                        <div id="" class="queueList" >
                            <div id="dndArea" class="placeholder">
                                <div id="filePicker"></div>
                            </div>
                        </div>
                    </div>
                    <div class="statusBar" style="display:none;">
                        <div class="progress">
                            <span class="text">0%</span>
                            <span class="percentage"></span>
                        </div><div class="info"></div>
                        <div class="btns">
                            <div id="filePicker2"></div><div class="uploadBtn">开始上传</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </li>
    <li>
        <ul id="imgs"></ul>
    </li>
</ul>




<%@ include file="/WEB-INF/views/ctrl/aliyunOSS/aliyunOSS.jsp"%>
<form:hidden id="url" path="pictureId" htmlEscape="false" maxlength="255" class="input-xlarge"/>

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部