我找不到使用ASP.Net Webpages 2在varbinary(max)上传文档到数据库的方法,我也想下载它。
到目前为止,我所拥有的是下面的内容,它应该将文件上传到网站上的目录,但它并没有做任何事情。任何帮助都会很棒。感谢
var fileName = "";
var fileSavePath = "";
int numFiles = Request.Files.Count;
int uploadedCount = 0;
for (int i = 0; i < numFiles; i++)
{
var uploadedFile = Request.Files[i];
if (uploadedFile.ContentLength > 0)
{
fileName = Path.GetFileName(uploadedFile.FileName);
fileSavePath = Server.MapPath("~/UploadedFiles/" +
fileName);
uploadedFile.SaveAs(fileSavePath);
uploadedCount++;
}
}
message = "File upload complete. Total files uploaded: " +
uploadedCount.ToString();
答案 0 :(得分:1)
以下代码位于您上传文件的页面顶部。请注意,您应根据数据库修改表和字段名称。此外,您应确保包含上传控件的表单将enctype
属性设置为multipart/form-data
:
@{
int id = 0;
var fileName = "";
var fileMime = "";
if (IsPost) {
var uploadedFile = Request.Files[0];
fileName = Path.GetFileName(uploadedFile.FileName);
if(fileName != String.Empty)
{
fileMime = uploadedFile.ContentType;
var fileStream = uploadedFile.InputStream;
var fileLength = uploadedFile.ContentLength;
byte[] fileContent = new byte[fileLength];
fileStream.Read(fileContent, 0, fileLength);
var db = Database.Open("FileUploading");
var sql = "INSERT INTO Files (FileName, FileContent, MimeType) VALUES (@0,@1,@2)";
db.Execute(sql, fileName, fileContent, fileMime);
}
}
}
要显示数据库中的文件,您需要一个单独的&#34;处理程序&#34;只包含此代码的文件:
@{
int id = 0;
if(Request["Id"].IsInt()){
id = Request["Id"].AsInt();
var db = Database.Open("FileUploading");
var sql = "Select * From Files Where FileId = @0";
var file = db.QuerySingle(sql, id);
if(file.MimeType.StartsWith("image/")){
Response.AddHeader("content-disposition", "inline; filename=" + file.FileName);
} else {
Response.AddHeader("content-disposition", "attachment; filename=" + file.FileName);
}
Response.ContentType = file.MimeType;
Response.BinaryWrite((byte[])file.FileContent);
}
}
此文件用作图像文件的src
属性,或用作指向应下载的文件(如PDF或Word文件)的链接的URL。如果您调用此处理程序文件&#34; download.cshtml&#34;,保存在数据库中的图像文件的链接应如下所示:
<img src="download.cshtml?Id=@id" alt="" />
其中Id参数值是数据库中文件的id。下载链接如下所示:
<a href="download.cshtml?Id=@id">Click Here</a>
所有这些都来自我的文章:http://www.mikesdotnetting.com/Article/148/Save-And-Retrieve-Files-From-a-Sql-Server-CE-Database-with-WebMatrix。具有SQL Compact数据库的文章之间的唯一区别是SQL CE中的文件的数据类型是image
而不是SQL Server中的varbinary(max)
。
答案 1 :(得分:0)
基于您的代码..您没有将图像上传到数据库。而是将图像保存在您的根目录/ UploadedFiles
中的文件夹上将图像存储在数据库中..您应该使用此代码..
using (Stream fs = uploadedFile.PostedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
string contentType = uploadedFile.PostedFile.ContentType;
SqlParameter[] arParams = new SqlParameter[2];
arParams[0] = new SqlParameter("@ID", SqlDbType.Int);
arParams[0].Value = 1; 'example
arParams[1] = new SqlParameter("@contentType", SqlDbType.Varchar(50));
arParams[1].Value = contentType;
arParams[2] = new SqlParameter("@document", SqlDbType.Varbinary(MAX));
arParams[2].Value = bytes;
SqlHelper.ExecuteNonQuery(SQLConn, CommandType.StoredProcedure, "Upload_Attachment", arParams);
}
}