I know how to upload a file and save it on the server as a physical file. I have successfully implemented this solution, there are lots of examples on the net.
Now I am searching for uploading a file and save it in a sql server database. Is it a totally different approach? I cannot find some examples on the net for this.
Any blogs/examples for a concrete implementation is welcome.
Thanks.
Below is my actual solution for uploading and saving a file on disk on the server (I am using the 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"));
}
}