如何使用xhr在angularjs中上传文件后获得响应

时间:2018-06-04 07:26:40

标签: asyncfileupload

我很难在文件上传后尝试从服务器获取对angularjs客户端的响应。我想将文件路径作为响应,以便我可以设置图像源属性。我没有使用angular $ http服务。 我想在xhr.onload函数之后得到响应

this.uploadIssueAttachment = function(attachment){
          var file, form, xhr;
          var file = attachment.file;
          form = new FormData();
          form.append('Content-Type', file.type)
          form.append('file', file)
          xhr = new XMLHttpRequest(); 
          //it is because we want t have to access of underlying XMLHttpRequest.. like tracking progress of file upload.
          xhr.open('POST', uploadUrl, true) //AJAX post request
          xhr.setRequestHeader('x-access-token', token)

          xhr.upload.onprogress = function(evt){
             var progress;
             progress = evt.loaded/ evt.total * 100; //progress %
             return attachment.setUploadProgress(progress)
          };
          //load  onload  --->The upload completed successfully.
          xhr.onload = function(){
            console.log('iam done uploading the files')
            var href,url;
            if (xhr.status === 204) { 
                //can u get the response link from the post request.
                console.log('server stuff', this.response) //undefined
               //url = href = host + key;  key is for the imageUrl part.
                //u can use imageUrl to set the attachment attributes.
                return attachment.setAttributes({
                   url: url,
                   href :href
                })

            }
          }

          xhr.onloadend= function(){
            console.log('iam finally done whether error or ...', xhr.response)
            //hey u need to ask on stackoverflow... how do i obtain the response from the server
            //ima doing it on angularjs... failed to get response after the file upload.
          }
          return xhr.send(form)
        }

1 个答案:

答案 0 :(得分:0)

在查看了一些github gists后,我终于得到了服务器的响应。 我想要解析作为json数据的响应。 NodeJS服务器。

res.json({"status":204, "message": filePath})

Angular客户。

xhr.onload = function(){
        console.log('iam done uploading the files')
        var href,url;
        if (this.status == 204) { 
            //can u get the response link from the post request.
             var res = JSON.parse(this.response) //this was the solution
           //url = href = host + key;  key is for the imageUrl part.
            //u can use imageUrl to set the attachment attributes.
            return attachment.setAttributes({
               url: url,
               href :href
            })

        }
      }