Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Ajax uploading a file and other values from client side [duplicate]

I need to upload a file to the server and send a GUID value, both needed to complete an operation.

Is it possible to send both with one $.ajax statement?

Here's a snippet of the Upload action method I'm using

[HttpPost]
public ActionResult Upload()
{
  HttpPostedFileBase file = Request.Files[0];
}

and here's a snippet of the Javascript code I'm using to send the file to the server

function upload() {
  var formData = new FormData();
  var totalFiles = document.getElementById("FileUpload").files.length;

  for (var i = 0; i < totalFiles; i++) {
    var file = document.getElementById("FileUpload").files[i];

    formData.append("FileUpload", file);
  }

  $.ajax({
    type: 'post',
    url: '/myController/Upload',
    data: formData,
    dataType: 'json',
    contentType: false,
    processData: false,
    success: function (response) {
      alert('succes!!');
    },
    error: function (error) {
      alert("errror");
    }
  });
}

This code is working well. The file is uploaded as expected but now I need to send a GUID to the same controller (Upload) so I wonder if I can send the GUID with the file in the same $.ajax statement?

like image 649
vcRobe Avatar asked Mar 03 '16 21:03

vcRobe


1 Answers

function upload() {
  var formData = new FormData();
  var totalFiles = document.getElementById("FileUpload").files.length;

  for (var i = 0; i < totalFiles; i++) {
    var file = document.getElementById("FileUpload").files[i];

    formData.append("FileUpload", file);
formData.append("guid", theGuid);
  }

  $.ajax({
    type: 'post',
    url: '/myController/Upload',
    data: formData,
    dataType: 'json',
    contentType: false,
    processData: false,
    success: function (response) {
      alert('succes!!');
    },
    error: function (error) {
      alert("errror");
    }
  });
}

on server side:

Request.Form["guid"];
Request.Files["FileUpload"];
like image 71
Ashkan Mobayen Khiabani Avatar answered Oct 30 '22 15:10

Ashkan Mobayen Khiabani