Best practice to send a lot of files (images) from your device to your server

时间:2017-03-22 18:46:32

标签: asp.net-web-api xamarin.forms threadpool

I have a list of files to send from my device to my server.

List<myFiles> list = new List<myFiles>() { "[long list of files...]" };

For that I want to create a list of tasks: for each file I should invoke a function that sends to my webapi that file via PUT

public async Task<bool> UploadPhoto(byte[] photoBytes, int PropertyId, string fileName)
{
    bool rtn = false;

    if (CrossConnectivity.Current.IsConnected)
    {
        var content = new MultipartFormDataContent();
        var fileContent = new ByteArrayContent(photoBytes);
        fileContent.Headers.ContentType = 
                            MediaTypeHeaderValue.Parse("multipart/form-data");
        fileContent.Headers.ContentDisposition = 
                            new ContentDispositionHeaderValue("attachment")
        {
            FileName = fileName + ".jpg"
        };
        content.Add(fileContent);

        string url = RestURL() + "InventoriesPicture/Put";

        try
        {
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("authenticationToken", SyncData.Token);
                HttpResponseMessage response = await client.PutAsync(url, content);
                if (response.IsSuccessStatusCode)
                {
                    rtn = true;
                    Debug.WriteLine($"UploadPhoto response {response.ReasonPhrase}");
                }
                else
                {
                    Debug.WriteLine($"UploadPhoto response {response.ReasonPhrase}");
                }
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine($"UploadPhoto exception {ex.Message}");
        }

        Debug.WriteLine($"UploadPhoto ends {fileName}");
    }

    return rtn;
}

In a function I have a foreach that calls UploadPhoto. I think there are too many tasks at the same time then I want to send a file, wait the result from the webapi and then send next file and so on.

What can I do? What is the best practice for that? Or in any case how can I resolve my problem? :) Thank you in advance

0 个答案:

没有答案