I've spent hours working many found examples without success for what is super simple to do in a web forms application. That is, upload one or more files and store them in sql server.
In web forms (vb.net) I can do this:
Dim fs As Stream = fileUpload1.PostedFile.InputStream
Dim br As New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(fs.Length)
'insert the file into database
Dim strQuery As String = "INSERT INTO files ([name], [type], [file]) VALUES (@Name, @ContentType, @Data)"
Dim cmd As New SqlCommand(strQuery)
cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename
cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value() = contenttype
cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes
Then do the database execute statements......done!
Now C# Web-Api:
The seemingly good example I have now that saves uploads to the filesystem via Web-Api is:
public Task<IEnumerable<FileDesc>> Old()
{
string folderName = "uploads";
string PATH = HttpContext.Current.Server.MapPath("~/" + folderName);
string rootUrl = Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.AbsolutePath, String.Empty);
if (Request.Content.IsMimeMultipartContent())
{
var streamProvider = new MultipartFormDataStreamProvider(PATH);
var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith<IEnumerable<FileDesc>>(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
var fileInfo = streamProvider.FileData.Select(i =>
{
var info = new FileInfo(i.LocalFileName);
return new FileDesc(info.Name, rootUrl + "/" + folderName + "/" + info.Name, info.Length / 1024);
});
return fileInfo;
});
return task;
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
}
}
I cannot seem to figure out how to get each multipart file content stream so that I can send to the database. I've seen posts talking about MultipartMemoryStreamProvider and MultipartStreamProvider but I haven't figured out how to use them. I'm clearly over my head as a C# and Web-Api newbie.
Can anyone direct me on how to get the file contents into a stream I can get the bytes to send to the db?
Here's my solution when I encountered this issue:
Client:
Controller: