我目前正在研究使用ASP.Net和C#爲web應用程序上傳和下載文檔到sql server 2008數據庫的不同方法和技術。使用asp.net上傳sql server 2008中的文檔C#
我發現這個excel tutorial,我想知道它是否類似於以類似的方式上傳PDF和Word文檔?
謝謝
我目前正在研究使用ASP.Net和C#爲web應用程序上傳和下載文檔到sql server 2008數據庫的不同方法和技術。使用asp.net上傳sql server 2008中的文檔C#
我發現這個excel tutorial,我想知道它是否類似於以類似的方式上傳PDF和Word文檔?
謝謝
答案很簡單:是的,它是相似的。
編輯
您發現鏈接是一個示例展示瞭如何存儲文件內容到數據庫,它可以改變其他任何不同的文件類型:PDF,DOC,JPG,不管,只要當你記錄mim e類型,以便下載最終用戶正確地得到它時
諷刺根本不聰明;) – phaazon
根本不諷刺,這是事實不是嗎? –
本教程適用於任何文件,而不僅僅是excel。最關鍵的是在這一部分:
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs); //reads the binary files
Byte[] bytes = br.ReadBytes((Int32)fs.Length); //counting the file length into bytes
query = "insert into Excelfiledemo(Name,type,data)" + " values (@Name, @type, @Data)"; //insert query
com = new SqlCommand(query, con);
com.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename1;
com.Parameters.Add("@type", SqlDbType.VarChar).Value = type;
com.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
com.ExecuteNonQuery();
Label2.ForeColor = System.Drawing.Color.Green;
Label2.Text = "File Uploaded Successfully";
什麼基本上是發生在這裏的是,文件流正在變成被存儲在數據庫中數據的blob的字節數組。這可以用於任何文件類型。只要確保文件名(至少是擴展名)與上面的示例一樣,以便在將文件恢復到磁盤上的文件時知道它是什麼類型的文件。
考慮到你分享的鏈接的例子中,使用下面的驗證:
switch (ext.ToLower())
{
case ".pdf":
type = "application/pdf";
break;
case ".doc":
type = "application/msword";
break;
case ".docx":
type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
}
Here是你可以考慮和All MIME Types你會發現一個更廣泛列表一些MS Office 2007的MIME類型。
當您先用代碼使用ASP.NET MVC 4或5時,此答案更合適。
//on your view model
public class MyViewModel
{
[Required]
[DisplayName("Select File to Upload")]
public IEnumerable<HttpPostedFileBase> File { get; set; }
}
// on your object class, make sure you have a data type byte[] that will store a file in a form of bytes, a byte[] data type store both Images and documents of any content type.
public class FileUploadDBModel
{
[Key]
public int Id { get; set; }
public string FileName { get; set; }
public byte[] File { get; set; }
}
// on your view
<div class="jumbotron">
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
@Html.LabelFor(x => x.File)
@Html.TextBoxFor(x => x.File, new { type = "file" })
@Html.ValidationMessageFor(x => x.File)
</div>
<button type="submit">Upload File</button>
}
</div>
//on your controller
public ActionResult Index(MyViewModel model)
{
FileUploadDBModel fileUploadModel = new FileUploadDBModel();
//uploading multiple files in the database
foreach (var item in model.File)
{
byte[] uploadFile = new byte[item.InputStream.Length];
item.InputStream.Read(uploadFile, 0, uploadFile.Length);
fileUploadModel.FileName = item.FileName;
fileUploadModel.File = uploadFile;
db.FileUploadDBModels.Add(fileUploadModel);
db.SaveChanges();
}
}
你是什麼意思類似的方式?你期待什麼答案? – phaazon