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; }

    }
Keval Patel
  • 925
  • 4
  • 24
  • 46
  • possible duplicate of [how to append whole set of model to formdata and obtain it in MVC](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc) –  Sep 11 '15 at 06:10
  • I cannot pass HttpPostedFileBase, because I am not using form tag. in object, can I add File too. ? – Keval Patel Sep 11 '15 at 06: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` –  Sep 11 '15 at 06:32
  • Correct, I did as you suggested, I am getting all data too, but not file. Please see my updated code – Keval Patel Sep 11 '15 at 06: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 files { get; set; }` –  Sep 11 '15 at 06:53
  • Great, Working (Y) :) Thanks a lot – Keval Patel Sep 11 '15 at 06:58
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/89435/discussion-between-keval-patel-and-stephen-muecke). – Keval Patel Sep 12 '15 at 04:18
  • I wrote it like this, string fileData = HttpContext.Current.Request.Form["fileData"]; and in js, var fileData = new Object(); fileData.UserId = 5; fileData.ArtCategory = $("#DropLevelCategory").val(); fileData.Title = $("#ArtTitle").val(); fileData.Description = $("#ArtDescription").val(); data.append("fileData", JSON.stringify(fileData)); – Keval Patel Sep 12 '15 at 05:09

1 Answers1

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
 }
tech-gayan
  • 1,373
  • 1
  • 10
  • 25