我需要在DownloadFile方法中对此代码进行编程,以自动选择应为PDF类型的文件。
当前,我必须在索引中的下载链接上单击“保存”,然后选择打开文件的文件类型,然后保存文件。如果我不选择文件类型,则会将其保存为未知文件。
请先完成此操作,谢谢。
/// <summary>
/// Retrive Image from database
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public ActionResult RetrieveImage(int id)
{
byte[] cover = GetImageFromDataBase(id);
if (cover != null)
{
return File(cover, "application.pdf");
}
else
{
return null;
}
}
/// <summary>
///
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
public byte[] GetImageFromDataBase(int Id)
{
var q = from temp in db.Contents where temp.ID == Id select temp.Image;
byte[] cover = q.First();
return cover;
}
[HttpPost]
public FileResult DownloadFile(int? fileId)
{
byte[] bytes;
string fileName, Description;
string constr = System.Configuration.ConfigurationManager.ConnectionStrings["dbContext"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT Title, Description, Image FROM [Contents] WHERE Id=@Id";
cmd.Parameters.AddWithValue("@ID", fileId);
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
bytes = (byte[])sdr["Image"];
Description = sdr["Description"].ToString();
fileName = sdr["Title"].ToString();
}
con.Close();
}
}
return File(bytes, Description, fileName);
}
public byte[] ConvertToBytes(HttpPostedFileBase image)
{
byte[] imageBytes = null;
BinaryReader reader = new BinaryReader(image.InputStream);
imageBytes = reader.ReadBytes((int)image.ContentLength);
return imageBytes;
}