javascript - Qiniuyun's upload image formdata form submission. Can multiple images be uploaded? How to do the specific logical method?
女神的闺蜜爱上我
女神的闺蜜爱上我 2017-06-14 10:54:17
0
1
1152

I have completed the form submission function for single upload, using their js-sdk, but now I want to upload multiple photos, how should I do it?

var f = new FormData(document.getElementById("testform"));

$.ajax({
  url: 'http://upload.qiniu.com/',  // Different bucket zone has different upload url, you can get right url by the browser error massage when uploading a file with wrong upload url.
  type: 'POST',
  data: f,
  processData: false,
  contentType: false,
  xhr: function(){
    myXhr = $.ajaxSettings.xhr();  
    if(myXhr.upload){
      myXhr.upload.addEventListener('progress',function(e) {
        if (e.lengthComputable) {
          var percent = e.loaded/e.total*100;
          $progress.html('上传:' + e.loaded + "/" + e.total+" bytes. " + percent.toFixed(2) + "%");
        }
      }, false);
    }
    return myXhr;
  },
  success: function(res) {
    var str = '<span>已上传:' + res.key + '</span>';
    if (res.key && res.key.match(/\.(jpg|jpeg|png|gif)$/)) {
      str += '<img src="' + domain + res.key + '"/>';
    }
    $uploadedResult.html(str);
  },
  error: function(res) {  
    $uploadedResult.html('上传失败:' + res.responseText);
  }
女神的闺蜜爱上我
女神的闺蜜爱上我

reply all(1)
左手右手慢动作

form里有多个file控件选择了文件的话,new FormData的时候就会包含多个文件。要上传多张的话在表单里选择多个文件就可以了。
不过这样的话sdk里的这些代码可能就不适用了,计算整体进度那部分没问题,但是seccess里的代码好像只适合处理单个图片。如果不需要上传后显示这个图片的话可以去掉显示图片的那部分代码。

如果要显示上传成功的图片,也可以考虑提交时不把整个form转换成FormData,而是先检查有多少个选择了文件的file控件,每个控件生成一个单独的FormData对象,最后依次调用这个sdk。

// 假设form里有多个file控件
// 先创建空的对象
var formData = new FormData();
// 将第一个file控件里的文件追加进去
formData.append('file',document.querySelector("#formID input[type=file]").files[0]);
// ...调用sdk的代码上传图片

// 依次循环……

这样的话sdk里的字符串要用累加的方式了,不过改起来简单

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!