예제 #1
0
        public async Task UploadFiles(IEnumerable <UploadFile> files, NameValueCollection values)
        {
            string newLine  = Environment.NewLine;
            string boundary = $"--{this.Boundary}";

            long totalBytes = files.Select(f => new FileInfo(f.FileName).Length).Sum();
            long sendBytes  = 0;

            if (values != null)
            {
                foreach (string name in values.Keys)
                {
                    await WriteString($"{boundary}{newLine}", Encoding.ASCII);
                    await WriteString($"Content-Disposition: form-data; name=\"{name}\"{newLine}{newLine}", Encoding.ASCII);
                    await WriteString($"{values[name]}{newLine}", Encoding.UTF8);
                }
            }

            foreach (UploadFile file in files)
            {
                await WriteString($"{boundary}{newLine}", Encoding.ASCII);
                await WriteString($"Content-Disposition: form-data; name=\"{file.Name}\"; filename=\"{Path.GetFileName(file.FileName)}\"{newLine}", Encoding.UTF8);
                await WriteString($"Content-Type: {file.ContentType}{newLine}{newLine}", Encoding.ASCII);

                using (var fs = File.OpenRead(file.FileName))
                {
                    byte[] buffer = new byte[4096];
                    int    read   = 0;

                    while ((read = await fs.ReadAsync(buffer, 0, buffer.Length)) > 0)
                    {
                        await RequestStream.WriteAsync(buffer, 0, read);

                        sendBytes += read;

                        this.OnReport(sendBytes / (double)totalBytes);
                    }

                    await WriteString(newLine, Encoding.ASCII);
                }
            }

            await WriteString($"{boundary}--", Encoding.ASCII);
        }
예제 #2
0
        private async Task WriteString(string value, Encoding encoding)
        {
            byte[] buffer = encoding.GetBytes(value);

            await RequestStream.WriteAsync(buffer, 0, buffer.Length);
        }