Children's shoes, please check the technical practice of [HttpClient sending files]
1. Empty cavity walking board
A few days ago, a children's shoe in the group asked: how to use HttpClient to send files?
Before, I wrote an ABP upload file, which mainly reflects the server. The action of uploading files is completed by the front-end little sister. I really haven't sent files by HttpClient programming.
However, the Web protocols are the same. Compared with the front-end sending files, httpclient can also be sent according to the multipart / form data media type.
I spent an hour reading the MDN Web protocol and wrote an example of HttpClient sending files, which was taken by the viewer.
2. Brainstorming
We follow the common idea of uploading files from forms to realize HttpClinet uploading files.
Multipart / form data is a multi part document format. Each part is divided by a boundary line (a string starting with '--'). It is also a request Media type MIME
As shown in the following form, there are three input form fields to be submitted
Check Send the file<form action="http://localhost:8000/" method="post" enctype="multipart/form-data"> <input type="text" name="myTextField"> <input type="checkbox" name="myCheckBox">Check</input> <input type="file" name="myFile"> <button>Send the file</button> </form>
Select a file and click the [Send the file] button to submit the form. The following request will be sent
Please observe each form field and value divided by boundary, where myFile is a file form field and one more content type.
3. Draw the ladle according to the gourd
The above is the protocol analysis of uploading files from conventional Html forms. Back to the topic of this article, this time, we will send a request containing only one file form field in the form of HttpClient encoding (multipart / form data media type still used), which is also the implementation idea below.
The following is the base64 encoding string of the image returned by the server when the httpclient uploads the file to the localhost:5000/upload address.
3.1 client
using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namespace ConsoleApp3 { class Program { static readonly HttpClient client = new HttpClient(); static async Task Main() { try { byte[] bytes; using (var bodyStream = new FileStream(@"D:\001.png", FileMode.Open)) { using var m = new MemoryStream(); await bodyStream.CopyToAsync(m); bytes = m.ToArray(); } // 1. Prepare file form fields and values var byteArrayContent = new ByteArrayContent(bytes); byteArrayContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/png"); // 2. Insert the prepared file form field value into MultipartFormDataContent. Note that MultipartFormDataContent is a collection type. var response = await client.PostAsync("http://localhost:5000/upload", new MultipartFormDataContent(Guid.NewGuid().ToString()) { { byteArrayContent, "uploadedFile", "\"001ggg.png\""} }); response.EnsureSuccessStatusCode(); var responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } catch (HttpRequestException e) { Console.WriteLine("\nException Caught!"); Console.WriteLine("Message :{0} ", e.Message); } } } }
- Please note that I use a Random GUID as the boundary of each form field. Here, I only insert a file form threshold into MultipartFormDataContent, so that HttpClient can send files.
- File form field value: {byteArrayContent, "uploadedFile", "\"001ggg.png \ ""} parameter 2: the field name is very important and should match the parameters of the following server.
3.2 server
The code of the uploaded file has been reflected in the article, and the core code of the uploaded file is intercepted and received this time
[Consumes("multipart/form-data")] [Route("upload")] [ProducesResponseType(typeof(Guid), 200)] [HttpPost] public async Task<string> UploadAsync(IFormFile uploadedFile) { var formFileName = uploadedFile.FileName; if (!new[] { ".png", ".jpg", ".bmp" }.Any((item) => formFileName.EndsWith(item))) { throw new NotImplementedException("The file format you upload must be png,jpg,bmp One of"); } byte[] bytes; using (var bodyStream = uploadedFile.OpenReadStream()) { using (var m = new MemoryStream()) { await bodyStream.CopyToAsync(m); bytes = m.ToArray(); } } var base64 = Convert.ToBase64String(bytes); return base64; }
Code a never lies and starts the client / server
3.3 giving people the right to fish
Mature technology must have mature debugging and monitoring means!
Mature technology must have mature debugging and monitoring means!
Mature technology must have mature debugging and monitoring means!
Whenever there is a block in web development, I take out the web weapon: Fiddler.
Go with Fiddler.
summary
- Upload files to conventional html forms and do source level analysis.
- According to the analysis results, HttpClient uses the same gesture to send files: it uses multipart / form data (multi part form media type) to initiate an upload request.
This article is from the blog Garden. The author: {attitudinal vest}. For reprint, please indicate the original link: https://www.cnblogs.com/JulianHuang/p/15697845.html