Click here to Skip to main content
16,022,352 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Requirement: Download zip from Browser

Currently I am able to create "Download.zip" file on destination folder ,but not able to download from Browser

Error: Faild to load resuorces "file\\D:\folderName\Download.zip"

Following is My Code
C#
  1  // Controller code 
  2  [HttpPost]
  3  public async Task<ActionResult> Downloadzip(List<FileViewModel> data)
  4  {
  5      string fileName = "";
  6      //string zipName = String.Format(fileName + ".zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
  7      string zipName = String.Format("Download.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
  8      string filenametodownload = "";
  9      string BatchID = System.Guid.NewGuid().ToString() + DateTime.Now.ToString("yyyyMMddhhmmss");
 10      string folderpath = System.IO.Path.Combine(ConfigurationManager.AppSettings["zipfilepath"].ToString());
 11  
 12      foreach (var file in data)
 13      {
 14          // Do something with each item in the array
 15          fileViewModel = new FileViewModel
 16          {
 17              Id = file.Id,
 18              FileName = file.FileName,
 19              FileContent = file.FileContent
 20          };
 21  
 22          lst1.Add(fileViewModel);
 23          Console.WriteLine(file);
 24      }
 25  
 26      for (int i = 0; i <= lst1.Count - 1; i++)
 27      {
 28          if (!string.IsNullOrEmpty(lst1[i].FileName))
 29          {
 30              //fileName = lst1[i].FileName.ToString().Substring(0, 8) + ".jpg";
 31              fileName = DateTime.Now.ToString("yyyy-MMM-dd-HHmmss")+ lst1[i].FileName;
 32  
 33              string filePath = System.IO.Path.Combine(folderpath, fileName);
 34  
 35              surveyFileRowInputIdInfo = new SurveyFileRowInputIdInfo();
 36              surveyFileRowInputIdInfo.row_id = lst1[i].Id.ToString();
 37              surveyFileRowInputIdInfo.DMSDoc_ID = "0";
 38              lst1[i].FileContent =  await GetBase64(surveyFileRowInputIdInfo);
 39  
 40              if (!string.IsNullOrEmpty(lst1[i].FileContent))
 41              {
 42                  lst1[i].FileContent = lst1[i].FileContent.Replace("data:image/jpeg:base64,", "");
 43                  lst1[i].FileContent = lst1[i].FileContent.Replace("data:image/jpeg;base64,", "");
 44  
 45                  if (lst1[i].FileContent != "NA")
 46                  {
 47                      System.IO.File.WriteAllBytes(filePath, Convert.FromBase64String(lst1[i].FileContent));
 48                  }
 49              }
 50          }
 51      }
 52  
 53      int fCount = Directory.GetFiles(folderpath, "*", SearchOption.AllDirectories).Length;
 54  
 55      try
 56      {
 57          if (fCount > 0)
 58          {
 59              using (ZipFile zip = new ZipFile())
 60              {
 61                  zip.AddDirectory(folderpath);
 62                  filenametodownload = Path.Combine(folderpath, zipName);
 63                  zip.Save(filenametodownload);
 64              }
 65          }
 66      }
 67      catch (Exception ex)
 68      {
 69          throw (ex);
 70      }
 71  }
 72  
 73  
 74  catch (Exception ex)
 75  {
 76      //LogSteps(ex.StackTrace, "");
 77      throw;
 78  }
 79  
 80  //Byte[] bytes1 = System.IO.File.ReadAllBytes(filenametodownload);
 81  //String file = Convert.ToBase64String(bytes1);
 82  // return Content(file, "application/zip");
 83  //  return File(bytes1, "application/zip", zipName);
 84  if (!string.IsNullOrEmpty(filenametodownload))
 85  {
 86      return Json(new { success = true, fileUrl = filenametodownload });
 87  }
 88  else
 89  {
 90      return Json(new { success = false, message = "No data to download" });
 91  }
 92  
 93  }

.cshtml code
JavaScript
function DownloadFile() {
    debugger;
    var pushData = [];
    //console.log(JSON.stringify(arlene1));
    for (var i = 0; i < arlene1.length; i++) {
        pushData.push({
            Id: arlene1[i].Id,
            FileContent: "",
            FileName: arlene1[i].FileName
        });
    }
    //console.log(JSON.stringify(pushData));

    $.ajax({
        url: '@System.Configuration.ConfigurationManager.AppSettings["WebAbsoluteURL"].ToString()' + "/ViewClaimStatus/Downloadzip",
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({ data: pushData }),
        success: function (response) {
            // Handle success
            console.log(response);
            window.location.href = response.fileUrl;
        },
        error: function (xhr, status, error) {
            // Handle error
            console.error(xhr.responseText);
        }
    });
}

Please Help me on this

What I have tried:

I tried many think , and changes many code but not able to crack any soltuion
Posted
Updated 19-Jun-24 22:22pm
v2

By the looks of it, you are attempting to download a file that sits outside your website. For security reasons, web applications are sandboxed into their own sites, and do not have access to folders outside this space. Try changing the behaviour of the application to download from inside your site folder structure.
 
Share this answer
 
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:
C#
return Json(new { success = true, fileUrl = filenametodownload });
JavaScript
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[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900