关于阿里云oss,FormData多图上传的问题?

1.在做上传多张图片的时候用的是阿里云oss,做多张的时候不知道怎么多张上传,就用了比较笨的方法,一张张for循环上传的,代码如下:
HTML:

 <div class="z_photo">
            <div class="z_file">
                <input type="file" name="imgfile" id="file" value="" accept="image/*" multiple="true" onchange="imgChange('z_photo','z_file');">
            </div>
        </div>

        <!--遮罩层-->
        <div class="z_mask" style="display: none">
            <!--弹出框-->
            <div class="z_alert">
                <p>确定要删除这张图片吗?</p>
                <p>
                    <span class="z_cancel">取消</span>
                    <span class="z_sure">确定</span>
                </p>
            </div>
        </div>

        <a href="javascript:;" class="send_btn" style="margin-top: 30px;" onclick="uploader()">发 表</a>

js:

var arr = [];
    var host,policy,signature,accessid,dir,expire,fileList,imgList;
    function uploader(){
        //将图片上传给服务器
        // $(".loading").show();
        $.showLoading();
        
        $.ajax({
            url :'https://x.sdp178.com/service/api.php?type=10098',  
            type : 'POST',
            contentType: false,  
            processData: false,  
            success:function (ret) {
                ret = eval("("+ret+")");
                host = ret.host;
                policy = ret.policy;
                signature = ret.signature;
                accessid = ret.accessid;
                dir = ret.dir;
                expire = ret.expire;
                ALIcloud(host,policy,signature,accessid,dir,expire);

            },
            error: function(xhr) {
                alert("错误提示: " + xhr.status + " " + xhr.statusText); 
            }
        });

    }

   function ALIcloud(host,policy,signature,accessid,dir,expire){
        //将图片上传给阿里云服务器
        for (var i = 0; i < imgList.length; i++) {
            var ossData = new FormData();
            ossData.append('OSSAccessKeyId', accessid);
            ossData.append('policy', policy);
            ossData.append('Signature', signature);
            ossData.append('key', dir);
            ossData.append('success_action_status', 201); // 指定返回的状态码
            ossData.append("file", fileList[i]);
            console.log(fileList[i]);
            $.ajax({
                url:host,  
                type:'POST',
                data:ossData,
                dataType: 'xml', // 这里加个对返回内容的类型指定
                processData: false,//不需要进行序列化处理
                async: true,//发送同步请求
                contentType: false,//避免服务器不能正常解析文件
                success:function (ret) {
                    var url = $(ret).find("Location").text();
                    console.log(url)
                    arr.push(url);
                   
                },
                error: function(xhr) {
                    alert("错误提示: " + xhr.status + " " + xhr.statusText); 
                }
            });
           
        }
        
        
    }
    

    function imgChange(obj1, obj2) {
        //获取点击的文本框
        var file = document.getElementById("file");
        //存放图片的父级元素
        var imgContainer = document.getElementsByClassName(obj1)[0];
        //获取的图片文件
        fileList = []
        fileList = file.files;
        //文本框的父级元素
        var input = document.getElementsByClassName(obj2)[0];
        var imgArr = [];
        //遍历获取到得图片文件
        if (fileList.length > 9) {
            $.toptips('抱歉,发表的图片不能超过9张!');
            return false;
        }else{
            console.log("fileList.length:"+fileList.length);
            
            for (var i = 0; i < fileList.length; i++) {
                var imgUrl = window.URL.createObjectURL(file.files[i]);
                imgArr.push(imgUrl);
                var img = document.createElement("img");
                img.setAttribute("src", imgArr[i]);
                var imgAdd = document.createElement("div");
                imgAdd.setAttribute("class", "z_addImg");
                imgAdd.appendChild(img);    
                imgContainer.appendChild(imgAdd);

            };
            imgRemove();
            
        };
    };
    
    
    function imgRemove() {
        imgList = document.getElementsByClassName("z_addImg");
        var mask = document.getElementsByClassName("z_mask")[0];
        var cancel = document.getElementsByClassName("z_cancel")[0];
        var sure = document.getElementsByClassName("z_sure")[0];
        console.log("imgList.length:"+imgList.length)
        for (var j = 0; j < imgList.length; j++) {
            imgList[j].index = j;
            imgList[j].onclick = function() {
                var t = this;
                mask.style.display = "block";
                cancel.onclick = function() {
                    mask.style.display = "none";
                };
                sure.onclick = function() {
                    mask.style.display = "none";
                    // t.style.display = "none";
                    $(t).remove();
                    
                };

            }
        };
    };

结果:
一次一次选择图片的时候,如图:

clipboard.png

clipboard.png

clipboard.png

一次性选择多张图片的时候则完全没有毛病,如图:

clipboard.png

问了下阿里云的售后工程师:
说一次只能上传一张,得循环上传。
clipboard.png

问题是该怎么给他循环呀,我现在的代码循环的话,一次选择多张点击发表没问题,一次点击选择一张然后再选择一张出来就有问题,因为文件长度为1,所以只返回一张图片正确的路径,其他的都是只返回路径。

已经搞定,js完整代码如下:

var arr = [];
    var host,policy,signature,accessid,dir,expire,fileList,imgList;
    var ossData = new FormData();
    function uploader(){
        //将图片上传给服务器
        // $(".loading").show();
        $.showLoading();
        
        $.ajax({
            url :'https://x.sdp178.com/service/api.php?type=10098',  
            type : 'POST',
            contentType: false,  
            processData: false,  
            success:function (ret) {
                ret = eval("("+ret+")");
                host = ret.host;
                policy = ret.policy;
                signature = ret.signature;
                accessid = ret.accessid;
                dir = ret.dir;
                expire = ret.expire;
                ALIcloud(host,policy,signature,accessid,dir,expire);

            },
            error: function(xhr) {
                alert("错误提示: " + xhr.status + " " + xhr.statusText); 
            }
        });

    }
    

    function ALIcloud(host,policy,signature,accessid,dir,expire){
        //将图片上传给阿里云服务器
        for (var i = 0; i < imgList.length; i++) {
            var ossData = new FormData();
            ossData.append('OSSAccessKeyId', accessid);
            ossData.append('policy', policy);
            ossData.append('Signature', signature);
            ossData.append('key', dir);
            ossData.append('success_action_status', 201); // 指定返回的状态码
            ossData.append("file", filearr[i]);
   
            $.ajax({
                url:host,  
                type:'POST',
                data:ossData,
                dataType: 'xml', // 这里加个对返回内容的类型指定
                processData: false,//不需要进行序列化处理
                async: false,//发送同步请求
                contentType: false,//避免服务器不能正常解析文件
                success:function (ret) {
                    var url = $(ret).find("Location").text();
                    arr.push(url);
                    if (arr.length == imgList.length) {
                        getPublish();
                    }
                },
                error: function(xhr) {
                    alert("错误提示: " + xhr.status + " " + xhr.statusText); 
                }
            });
           
        }  
    }
    
    //选择图片
    var filearr = [];
    function imgChange(obj1, obj2) {
        //获取点击的文本框
        var file = document.getElementById("file");
        //存放图片的父级元素
        var imgContainer = document.getElementsByClassName(obj1)[0];
        //获取的图片文件
        fileList = file.files;
        //文本框的父级元素
        var input = document.getElementsByClassName(obj2)[0];
        var imgArr = [];
        //遍历获取到得图片文件
        if (fileList.length > 9) {
            $.toptips('抱歉,发表的图片不能超过9张!');
            return false;
        }else{
            for (var i = 0; i < fileList.length; i++) {
                var imgUrl = window.URL.createObjectURL(fileList[i]);
                imgArr.push(imgUrl);
                filearr.push(fileList[i]);
                var img = document.createElement("img");
                img.setAttribute("src", imgArr[i]);
                var imgAdd = document.createElement("div");
                imgAdd.setAttribute("class", "z_addImg");
                imgAdd.appendChild(img);    
                imgContainer.appendChild(imgAdd);
            };

            imgRemove();
            
        };
    };
    
    //删除图片
    function imgRemove() {
        imgList = document.getElementsByClassName("z_addImg");
        var mask = document.getElementsByClassName("z_mask")[0];
        var cancel = document.getElementsByClassName("z_cancel")[0];
        var sure = document.getElementsByClassName("z_sure")[0];
     
        for (var j = 0; j < imgList.length; j++) {
            imgList[j].index = j;
            imgList[j].onclick = function() {
                var t = this;
                mask.style.display = "block";
                cancel.onclick = function() {
                    mask.style.display = "none";
                };
                sure.onclick = function() {
                    mask.style.display = "none";
                    // t.style.display = "none";
                    $(t).remove();
                };

            }
        };
    };
阅读 5.7k
2 个回答

多图上传用formdata,把上传的图片放在一个数组里,你的fromdata应该放在for循环外面,ajax也应该放在外面,append改成 ossData.append("file[]", fileList[i]);,还可以对其进行删除重选等操作,最后一次性上传,可参考我写的图片上传的博客链接

var filearr = [];   //这个装添加的图片,要放在onchange外面
var myfile = document.getElementById('file');

onchange
myfile.onchange = function(){
    var files = this.files; 
    for(var i = 0;i<files.length;i++){                
         filearr.push(files[i]);
         //这里就进行添加图片的预览操作     
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题