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?

share
    
It must be too cutting edge and I've never had an SO question not answered before. I had to switch to using a webforms project and HttpHandler's. I'm sure there is a way to do this but projects must get done. :-( – JoelCool Oct 5 '13 at 23:14

Here's my solution when I encountered this issue:

Client:

 public async Task UploadImage(byte[] image, string url)
        {
            Stream stream = new System.IO.MemoryStream(image);
            HttpStreamContent streamContent = new HttpStreamContent(stream.AsInputStream());

            Uri resourceAddress = null;
            Uri.TryCreate(url.Trim(), UriKind.Absolute, out resourceAddress);
            Windows.Web.Http.HttpRequestMessage request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, resourceAddress);
            request.Content = streamContent;

            var httpClient = new Windows.Web.Http.HttpClient();
            var cts = new CancellationTokenSource();
            Windows.Web.Http.HttpResponseMessage response = await httpClient.SendRequestAsync(request).AsTask(cts.Token);
        }

Controller:

public async Task<HttpResponseMessage> Post()
{
    Stream requestStream = await this.Request.Content.ReadAsStreamAsync();
    byte[] byteArray = null;
    using (MemoryStream ms = new MemoryStream())
    {
        await requestStream.CopyToAsync(ms);
        byteArray = ms.ToArray();
    }
    .
    .
    .
    return Request.CreateResponse(HttpStatusCode.OK);
}
share

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.