I have an MVC5 project, and it has a view that allows a user to download documents from SQL Server. This view is a form page with one or more file input controls that allow a user to upload any file types. When a user selects a file from the desktop and puts it into the input file box and clicks on the submit button, the file is converted into a byte[] type and saved into SQL Server. After the file is uploaded, the user opens the same page again, and the download link appears in the control. If a user clicks on it, the file isn’t saved onto their desktop, but if the user right-clicks on the link and opens it in a new tab, the file can be downloaded. Here is the following snippet from the view page that allows user to download files from upload control:
FillTemplateFields.cshtml
@{
string[] fileUploadItems = @value.Split(',');
}
@for (int k = 0; k < @fileUploadItems.Length; k++)
{
<div id="fileContainer-@count">
@if(fileUploadItems[k] != null){
<input id="sub-file-@count" type="file" value="@fileUploadItems[k]" placeholder="@control.Placeholder" name="fileUpload-@count" data-sub-channel="sub-input-@count">
@Ajax.ActionLink("Download " + @fileUploadItems[k], "DownloadFile", new { fieldID = @count, fileName = @fileUploadItems[k] }, null)
<br />
}
else
{
<input id="sub-file-@count" type="file" value="" placeholder="@control.Placeholder" name="fileUpload-@count" data-sub-channel="sub-input-@count">
}
<a id="deleteControl-@count" href="#">Delete</a>
The ‘fileUploadItems’ object contains the file names saved into the upload control. The Ajax.ActionLink helper creates a link that calls for the ‘DowloadFile’ method, which passes the the values of the fielded and the name of the file, and finds the file that was saved onto Sql Server:
TemplateValuesController.cs
public FileResult DownloadFile(int fieldID, string fileName)
{
tbl_FileStorage file = db.tbl_FileStorage.Where(f => f.FileName == fileName && f.TemplateFieldValuesID == fieldID).First();
return File(file.File, System.Net.Mime.MediaTypeNames.Application.Octet, file.FileName);
}
I can download the file successfully by right-clicking on the download link and opening it on new tab, but I can’t download it while staying on the same page, and I’m not trying to stream the file on a new browser tab. Can someone give me solutions to what I want? Thank you.