0

I am uploading file and for that I am using FormData object in jquery ajax and passing it to the ASP.NET MVC WEB API, It's working fine, I am able to get files on server side, but I want to pass some extra details too with same request.

I can add additional data in headers and I am able to fetch on server side from headers but I will use same API's for mobile app too. So if I can pass data as a parameter of function, then it would be nice.

So how to pass additional data in formData object and how to fetch it on server side ?

My code is,

function uploadEvaluationFile() {

    var files = $("#file_UploadFile1").get(0).files;
    if (files.length > 0) {
        if (window.FormData !== undefined) {
            var data = new FormData();
            for (var x = 0; x < files.length; x++) {
                data.append("file1" + x, files[x]);
            }


data.append("UserId", 5);
            data.append("ArtCategory", 5);
            data.append("Title", "Title1");
            data.append("Description", "Desc 1");

            $.ajax({
                type: "POST",
                url: '/Home/saveEvaluationFile',
                contentType: false,
                processData: false,
                data: data,
                async: false,
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('identifier', 111);
                    xhr.setRequestHeader('oldFileName', 222);
                },
                dataType: "json",
                success: function (result) {
                    console.log(result);
                },
                error: function (err) {
                    console.log(err);
                }
            });
        } else {
            alert("This browser doesn't support HTML5 file uploads!");
        }
    }
}

web api code,

[HttpPost]
        public async Task<JsonResult> saveEvaluationFile(EvaluationFileDetails FileData)
        {
            IEnumerable<string> headerValues = Request.Headers.GetValues("oldFileName");
            var oldFileName = headerValues.FirstOrDefault();
            IEnumerable<string> headerValues1 = Request.Headers.GetValues("identifier");
            var newFileName = headerValues1.FirstOrDefault();

            try
            {
                foreach (string file in Request.Files)
                {
                    HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                }
            }
            catch (Exception)
            {
                return Json("Upload failed");
            }

            return Json("File uploaded successfully");
        }

My class is,

public class EvaluationFileDetails
    {
        public HttpPostedFileBase file1 { get; set; }
        public int UserId { get; set; }
        public int ArtCategory { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }

    }
8
  • possible duplicate of how to append whole set of model to formdata and obtain it in MVC Commented Sep 11, 2015 at 6:10
  • I cannot pass HttpPostedFileBase, because I am not using form tag. in object, can I add File too. ? Commented Sep 11, 2015 at 6:28
  • 1
    Not sure what you mean. You can pass whatever you want using FormData. But you will find this a lot easier if you just add parameters to you method (e.g. a model) so you don't have access values form Request Commented Sep 11, 2015 at 6:32
  • Correct, I did as you suggested, I am getting all data too, but not file. Please see my updated code Commented Sep 11, 2015 at 6:51
  • 1
    Because you have named them file10, file11, file12 etc. You need to just name them (say) files and then the model needs to be public IEnumerabe<HttpPostedFileBase> files { get; set; } Commented Sep 11, 2015 at 6:53

1 Answer 1

2

You can use Same like

 data.append("file1" + x, files[x]);

Ex:

 formdata.append('Key', 'Value');

To fetch the data

[HttpPost]
public async Task<JsonResult> saveEvaluationFile(FileModel model)
{
  foreach (string image in model.images)
  {
     HttpPostedFileBase hpf =  model.images[image ] as HttpPostedFileBase;
    // nesasary save part
  }

add file to Model

 public class FileModel
 {
 ...
 public HttpPostedFileBase File1 { get; set; }//one file
 public IEnumerable<HttpPostedFileBase> images {get;set;}//file collection
 }
Sign up to request clarification or add additional context in comments.

5 Comments

in Model object, can I add File too. ?
Please check my updated question, I added class, and I am getting all data except file. file1 property is null on server side
First thing you need to do is make the file property as collection as i suggest in my code public IEnumerable<HttpPostedFileBase> images {get;set;}//file collection
Good solution. Superb!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.