我知道如何上传文件并将其作为物理文件保存在服务器上。我已经成功实现了这个解决方案,网上有很多例子。
现在我正在搜索上传文件并将其保存在 sql server 数据库中。这是一种完全不同的方法吗?我在网上找不到一些例子。
欢迎任何具体实现的博客/示例。
谢谢。
以下是我在服务器上的磁盘上上传和保存文件的实际解决方案(我使用的是 MultipartFormDataStreamProvider):
[HttpPost]
public Task<HttpResponseMessage> Post()
{
string RootPath = HttpContext.Current.Server.MapPath("~/" + RootFolder);
if (Request.Content.IsMimeMultipartContent())
{
var streamProvider = new CustomMultipartFormDataStreamProvider(RootPath);
var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith<HttpResponseMessage>(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
// Move the file to the right destination depending on the type (defined client side)
string type = streamProvider.FormData.GetValues("type").FirstOrDefault();
string fullname = streamProvider.FormData.GetValues("fullname").FirstOrDefault();
FileType fileType;
if (!Enum.TryParse<FileType>(type, out fileType))
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "The file type is incorrect"));
}
var DestPath = RootPath + "\\" + GetFolderName(fileType);
if (!Directory.Exists(DestPath))
Directory.CreateDirectory(DestPath);
var fileInfo = streamProvider.FileData.Select(i =>
{
var info = new FileInfo(i.LocalFileName);
var fileName = fullname + info.Extension;
var srcFile = RootPath + "\\" + info.Name;
var dstFile = DestPath + "\\" + fileName;
var filesize = info.Length;
switch (fileType)
{
case FileType.DriverCertificate:
if (File.Exists(dstFile))
File.Delete(dstFile);
File.Move(srcFile, dstFile);
break;
default:
break;
}
return new FileDescription(fileName, DriverCertificatesFolder + "/" + fileName, filesize / 1024);
});
return new HttpResponseMessage()
{
Content = new JsonContent(new
{
Success = true,
Data = fileInfo
})
};
;
});
return task;
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
}
}