0

这里是 mu uploadFile 函数

function uploadFile(options){
  var formData = new FormData();
  formData.append(options.paramName, options.file);
  if(options.data){
    for(var k in options.data){
      formData.append(k, options.data[k]);
    }
  }

  sendRequest(formData, options.url);

  function sendRequest(formData, url){
    var xhr = new XMLHttpRequest();

    // Set up events
    xhr.upload.addEventListener('loadstart', onloadstartHandler, false);
    xhr.upload.addEventListener('progress', onprogressHandler, false);
    xhr.upload.addEventListener('load', onloadHandler, false);
    xhr.addEventListener('readystatechange', onreadystatechangeHandler, false);

    // Set up request
    xhr.open('POST', url, true);
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    xhr.setRequestHeader('X-CSRFToken', getCookie('csrftoken'));

    xhr.send(formData)
  }
  function onloadstartHandler(evt){
  }
  function onprogressHandler(evt){

  }
  function onloadHandler(evt){
  }
  function onreadystatechangeHandler(evt){
    if(evt.target.readyState == 4){
      var status = evt.target.status;
      if(evt.target.responseText){
        options.handler(evt.target);
      }
    }
  }
}

我正在从文件输入的“更改”处理程序中调用上述函数,如下所示 -

'change input#user_pic': function(ev){
      var selfRef = this;
      var fel = ev.currentTarget;
      if(fel.files.length>0){
        var file = fel.files[0];
        uploadFile({
          paramName: 'photo',
          file: file,
          url: '/'+eventRouter.eventId+'/photos/upload/',
          handler: function(xhr){
            if(xhr.status == '200'){
              var img = $.parseJSON(xhr.responseText)['photo'];
              selfRef.model.set({picture: img});
              console.log('photo uploaded');
              console.log(img);
            }
          }
        });
      }
    }

Chrome 说失败,而 Firefox 说中止。没有显示错误或异常。我不知道为什么请求失败。

这是我在 chrome n/w 选项卡中看到的

Request URL:http://localhost:8000/5/photos/upload/
Request Headersview source
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryg6rSLttylr9m2Yla
Origin:http://localhost:8000
Referer:http://localhost:8000/events/edit/5
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31
X-CSRFToken:qTiEOg9wGFHxEtQV5EyW612DEh9qgooN
X-Requested-With:XMLHttpRequest
Request Payload
------WebKitFormBoundaryg6rSLttylr9m2Yla
Content-Disposition: form-data; name="photo"; filename="Koala.jpg"
Content-Type: image/jpeg


------WebKitFormBoundaryg6rSLttylr9m2Yla--

它只是说状态失败。

4

0 回答 0