levkaster
levkaster

Reputation: 2730

Upload file using Dojo and c# using xhr Post

I'm trying to upload file using dojo/_base/xhr here is the code:

 xhr.post({
                url: postUrl,
                handleAs: "text",
                contentType: "application/json",
                timeout: 10000,
                postData: dojo.toJson({ file: Uploader.files[0]}),
                load: function (result) {
                    show image...
                },
                error: function (err) {
                    show error...
                }
            });

when I try to send Uploader.files[0].size I get the value I should get, but when I try to send Uploader.files[0] or Uploader.files[0] I get null.

On the server side:

[HttpPost]
public string UploadImg(string file)
{
`   Saving file
}

I tried everything!! But I can't manage to get the file itself. Request.Files returns 0 files. Submitting a form isn't an option and when I use

 xhr.post({
                form: dom.byId("myform"),
                handleAs: "text",
                timeout: 10000,
                load: function (result) {
                    show image...
                },
                error: function (err) {
                    show error...
                }

Request.Files returns 0

Upvotes: 0

Views: 1648

Answers (2)

Ricardo Garza V.
Ricardo Garza V.

Reputation: 909

ajax is not a viable option for crossbrowser file async upload. you should try using the module:

http://dojotoolkit.org/reference-guide/1.8/dojo/request/iframe.html

http://dojotoolkit.org/reference-guide/1.9/dojo/request/iframe.html

and make them submit your form to a hidden iframe.

iframe(postUrl,{
  form: "theForm",
  handleAs: "text"
}).then(function(data){
  show image...
},function(err){
  show error...
});

just remember that if you need to do something with the returning data(and is not html [like in your text case]) you need to do this for the response:

<html>
  <body>
    <textarea>
         data
    </textarea>
  </body>
</html>

Upvotes: 1

HELLO23
HELLO23

Reputation: 16

You could try using HttpPostedFileBase :

[HttpPost]
public string UploadImg(HttpPostedFileBase file) {
   //Save the file :
   if (file != null && file.ContentLength > 0) {
      file.SaveAs(path);
   }
}

See this StackOverflow answer, and this article


You could also try removing the dojo.toJson :

postData: { file: Uploader.files[0]}

Instead of :

postData: dojo.toJson({ file: Uploader.files[0]})

Upvotes: 0

Related Questions