Jerzy Gawor
Jerzy Gawor

Reputation: 151

MVC: Download file and return model from same action

I have to download file and return with the file some data in a model.

I was research it, but I couldn't find any result to do this. For now I can say "It is not possible", but maybe some of you can answer on my question. I need something like:

...return Json(new {data:"some string", File("some.zip")});

Also, I am using an angularJS in the client side. So to connect with the server I am using $http statement and as responseType I have "arraybuffer".

Upvotes: 0

Views: 190

Answers (1)

cl3m
cl3m

Reputation: 2801

You could base64 encode your file, and send it as a JSON property:

Byte[] bytes = File.ReadAllBytes("path");
String file = Convert.ToBase64String(bytes);

// JObject from Newtonsoft Json.net library
var json = new JObject
{
    {"data","some data" },
    {"file", file },
    // You could add some file properties as well :
    {"filesize": 54836 },
    {"filetype": "image/jpeg"},
    {"filename": "profile.jpg"},
};

return Json(json, JsonRequestBehavior.AllowGet);

Then, in your angular / javascript code, you can refer to this article (untested) to convert back your encoded file.

Upvotes: 1

Related Questions