(ASP NET MVC4 or 5) How to pass a custom name through XMLHttpRequest?

3

Personally the question is as follows, I have a <input type="file" id="fileupload"/> and a <input type="text id="Nome"/> field. To pass it to my controller, I do the following:

var data = $("#fileupload").get(0).files[0];
var formdata = new FormData();
formdata.append("Files", data);
var xhr = new XMLHttpRequest();
xhr.open("POST", "/Home/UploadFiles", true);
xhr.send(formdata);

So far so good, the problem is that I wanted, along with the file, to pass the user-entered name in the "Name" element. There on the other side I would save it with the new name (holding the extension) somewhere. I tried everything and could not pass the name ... How can I do it?

Thanks in advance!

Obs: Gypsy Morrison, my controller is this:

[HttpPost]
public ContentResult UploadFiles()
{
    //Pego o arquivo
    HttpPostedFileBase hpf = Request.Files[0] as HttpPostedFileBase;

    //Pego a extensao dele para selecionar o tipo
    string extensao = hpf.FileName.Substring(hpf.FileName.Length - 4).ToLower();

    //Seleciono o tipo de arquivo e retorno se não for o que eu quero
    if (!(extensao == ".jpg" || extensao == ".gif" || extensao == ".png" || extensao == ".pdf"))
    {
        return Content("{\"success\":\"" + false + "\",\"message\":\"" + "Estensão não permitida!" + "" + "\"}", "application/json");
    }

    //Configuro o nome do arquivo para salvá-lo (nessa parte eu realmente queria o nome passado pelo usuário)
    string fileName = hpf.FileName.Replace(" ","").Replace(".","").Replace("'","").ToUpper() + "-" + String.Format("{0:yyyyMMddhhmmss}", DateTime.Now) + extensao;

    //Salvo o arquivo
    string savedFileName = Path.Combine(Server.MapPath("~/Empresa"), fileName);
    hpf.SaveAs(savedFileName);
    return Content("{\"success\":\"" + true + "\",\"message\":\"" + "Upload finalizado com sucesso!" + "" + "\"}", "application/json");

}
    
asked by anonymous 04.06.2014 / 23:26

1 answer

4

Add to FormData :

var formdata = new FormData();
formdata.append("Files", data);
formdata.append("Nome", $("#Nome").val());

And to Controller :

[HttpPost]
public ContentResult UploadFiles(String Nome)
{ ... }

I'm assuming you have at least in the project.     

04.06.2014 / 23:52