Well, for a start, you have a lot of code outside of your method, which is invalid. I'm assuming that's just a copy/paste error in your question.
Quote:
catch (Exception ex)
{
throw (ex);
}
Don't do this! You've just thrown away the entire stack trace of the exception, making your life much harder when you want to track down the real source of the error.
If you really want to re-throw an exception, use
throw;
instead of
throw ex;
.
But in this case, since you're not doing anything with the exception, just remove the
try..catch
block. There's no need to catch an exception unless you're going to do something with it!
Quote:
return Json(new { success = true, fileUrl = filenametodownload });
window.location.href = response.fileUrl;
Your C# code is running on the server. It is returning the full path of the ZIP file you have saved
on the server (
D:\FolderName\Download.zip
).
The JavaScript code is running on the client. You are trying to navigate the browser to that file
on the client.
Even assuming the browser allows navigation from a website to a file path, the chances are that the client
will not have a file in that path. They may not even have a
D:
drive.
And even if they
do have a file in that path, it is highly unlikely to contain the same contents as your copy of the file on the server.
NB: It might
appear to work when you debug in Visual Studio. But that's only because, in that specific scenario, the client and server are the same computer.
Also note that you're using the same folder path for every request. If two users call your action at the same time, their requests will interfere with each other. At best, you will get an exception indicating that a file is in use; at worst, each user will receive data related to another user's request, and you have an information disclosure vulnerability in your site.
If you want the client to download a file, you cannot simply save it to a folder on the server and tell the client to navigate to that folder. You have to transmit the file in the response, including the appropriate
Content-Type
header to tell the client what type of file you're sending.
Simplistically, you would replace
return Json(...)
with
return File(filenametodownload, System.Net.Mime.MediaTypeNames.Application.Zip);
- but either use a unique folder for each request, or switch to generating the files and the final zip file entirely in-memory to avoid requests from interfering with each other.
On the client side, this will be complicated by the fact that you're using an AJAX request to initiate the download. You can see various suggestions on how to deal with that in
this StackOverflow thread[
^].