I have a following method inside a viewcomponent
public async Task<IViewComponentResult> InvokeAsync (ToolModel model)
{
if (!ModelState.IsValid)
{
return View();
}
//Code
return await Task.FromResult((IViewComponentResult)View(FullPathsOfViews.FileDownload, fileName));
}
There is an another view called Download and I want to redirect to this View after executed the above code, Also need to send the fileName via URL and catch it from the download controller.
Here is the download controller
[HttpPost]
[Route("download/{file}")]
public async Task<IActionResult> Download(string fileName)
{
string fileName = HttpContext.Request.Query["download"].ToString();
string wwwPath = string.Empty;
string FilePath = string.Empty;
wwwPath = this.env.WebRootPath;
FilePath = string.Format("{0}\\file-convertions\\{1}", wwwPath, fileName);
byte[] fileBytes = null;
// Download Word file
if (!string.IsNullOrEmpty(FilePath))
{
fileBytes = System.IO.File.ReadAllBytes(FilePath);
}
return File(fileBytes, "application/force-download", "ddd");
}
I want to URL be like
https://www.test.com/download/rt82x3267skykv34l8b3x4rnrrz1yz0g4cssd.pdf
How to achieve this? I am a beginner
Well, based on your comment and previous qustion it appeared that, you want to upload file using the viewcomponent and after uploading you want a download link back to the viewcomponent. If so you can achieve that using the same viewcomponent.
What we will achieve:
Let's assume, we have view component as following:
We want to upload a file and then want to show a download link back to the same view compoent as following:
How to achieve:
All you need a model with download property name where we would be passing either downloaded file or full link (I would prefer file name to pass in download controller as a parameter). Finally, within the viewcomponent using anchor tag along with <a asp-action will can redirect to download page.
Let's have a look in action how we can implement that;
Model:
Note: For my demo I have used above property but IFormFile and DownloadLink are our main foucs. You can customize as per your need.
View Component:
Note: As you can see, I am using a conditional and at the beginning not showing any file info or download link, after executing upload action it will be rendered with our download link/fine name and other info we want. Point that, we are using asp action and passing controller parameter as asp-route-downloadlink="@Model.DownloadLink".
Controller action when upload :
Note: Here, I am uploading file in a wwwroot folder and I have that location which I can pass to the download controller action, it could full link or only file name. I prefer fine name because I can directly extract the file by file name from directory. I have following directory:
Download action within same controller:
Output:
Note: Furthermore, you could explore few additional helpful resources here in official document.