2

I'm working on an Android App which communicates with a WebApi .NET project in order to insert and get date from database, common case. I've tried to use Multipart MIME. So I've used the following code:

public async Task<HttpResponseMessage> ManageProfilePicture()
    {
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }
        string root = HttpContext.Current.Server.MapPath("~/App_Data");
        var provider = new MultipartFormDataStreamProvider(root);

        var task = await Request.Content.ReadAsMultipartAsync(provider).
            ContinueWith<HttpResponseMessage>(t =>
            {
                if (t.IsFaulted || t.IsCanceled)
                {
                    Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
                }

                String fileName = provider.FileData[0].Headers.ContentDisposition.FileName;
                return Request.CreateResponse(HttpStatusCode.OK);
            });

        return task;
    }

I'm able to get the file name and other informations about the uploaded file. How could I get the byte array associated to the uploaded file in order to save it in MS SQL Server ? Maybe it's better to recreate the picture in a accessable folder than store it in the database...

Someone could help me with that ?

Hubert Solecki
  • 2,611
  • 5
  • 31
  • 63
  • It's not clear whether you want to know how to send image as a byte array to a Web API or how to save the byte array into SQL Server. Also, provide some code of what you already tried. – jpgrassi Dec 27 '15 at 22:50
  • 1
    To upload the picture I wouldn't use JSON. Use mutlipart-form upload and base64 encode the picture. Trying to upload a massive photo in straight JSON usually blows out any JSON parser. at least thats been my experience on the Web. Never done it on an android app. – ThrowsException Dec 28 '15 at 07:39
  • @ThrowsException Thank you for your answer, I've updated my question as I have implemented the multipart-form... Could you give me some advice ? – Hubert Solecki Dec 28 '15 at 13:24

1 Answers1

4

For your requirement, you can refer to the following sample code:

            // process incoming request            
            if (!Request.Content.IsMimeMultipartContent())
            {                
                // return error response               
            }

            // read the file and form data.
            ...
            await Request.Content.ReadAsMultipartAsync(provider);                           
            ...

            // check if files are on the request.
            if (provider.FileStreams.Count == 0)
            {                
                // return return error response               
            }

            IList<string> uploadedFiles = new List<string>();

            foreach (KeyValuePair<string, Stream> file in provider.FileStreams)
            {
                // get file name and file stream
                byte[] photo;
                string fileName = file.Key;
                using (Stream stream = file.Value)
                {
                    using (BinaryReader reader = new BinaryReader(stream))
                    {
                        photo = reader.ReadBytes((int)stream.Length);
                    }
                }

                // INSERT INTO DATABASE HERE (USING SqlConnection, SqlCommand...)                
                // ...

                // keep track of the filename and filelength for the response
                uploadedFiles.Add(fileName);
                uploadedFiles.Add(photo.Length.ToString("N0") + " bytes");
            }

            // return successful response;

Hope it helps!

P/S: you can read more here.

Community
  • 1
  • 1
BNK
  • 23,994
  • 8
  • 77
  • 87