如何从任何类型的数据库(pdf、xlx、jpg 或 png)中检索文件并使其可在网页上下载?

How to retrieve file from Database of any type(pdf,xlx,jp or png) and make it download-able on webpage?

我正在使用 SQL Server Management Studio。在我的 table 中有一个数据类型为 varbinary(max) 的列。我已成功将特定格式的文件(pdf、xlx、jp 或 png)上传到我的table。但是现在我很难取回它。我正在使用 ASP.NET。我需要制作一个控制器,它可以通过 LINQ 从数据库中获取文件并将其下载到用户的计算机上。

有很多关于这个问题的教程包含耗时的答案,这些答案可能会或可能不会处理当前情况。 因此,这是您需要分步执行的操作:

  1. 在JavaScript中通过以下步骤将采集到的数据发送给控制器:
var file = document.getElementById("---id of the insert tag where document is loaded").files[0];

然后使用 FormData 文件(变量)附加到表单。

formData = new FormData();
formData.append("file",file);     

当我们向控制器发送数据时,formData 作为一对 key:value 工作。 现在通过 ajax:

将数据发送到控制器
$.ajax({
    url: "--url--",
    data: formData,
    type: "POST"
...

现在在 URL 中提到的控制器中,确保它包含与 file 中提到的同名参数formData.append("file",file); 。该文件的数据类型将为 HttpPostedFileBase。控制器将如下所示:

 [HttpPost]
 public ActionResult SaveFile( HttpPostedFileBase file)
  {
//The below mentioned code will convert file in byte[] which can be transferred to database
       using (Stream inputStream = file.InputStream)
        {
          MemoryStream memoryStream = inputStream as MemoryStream;
          if (memoryStream == null)
           {
              memoryStream = new MemoryStream();
              inputStream.CopyTo(memoryStream);
           }
                        byteValue = memoryStream.ToArray();// datatype = byte[]
        }
  }         

现在通过在服务器上创建文件然后通过提供文件在服务器上的路径将该文件进一步发送给用户来从数据库中检索文件。

filePath = Path.Combine(HttpContext.Current.Server.MapPath("-----Location where you want to save file----"),"---Name of file with extention---");//filePath will create the path. Note: it's just a path.
MultiPurpose.DeleteExistingFile(filePath);// It will delete pre-existing file if already present on the path with same name
System.IO.File.WriteAllBytes(filePath, db.file);// It will create the file present on database with datatype 'byte[]'
return File(filePath ,Content-Type, "--you can mention new file name here---"); // This will download the file on user's pc with the file name mentioned in third parameter.