In the past two days, a winform program is required to upload data to the server. At that time, the first idea was to implement it through the webservice method. Later, I felt troublesome. I didn't use this method if I wanted to be lazy. The http post method became the first choice. In the past, I used httpwebrequest and other things for post submission. winform is really the first time, but soon I found the webclient class on the Internet. Next I started to implement the function, it is really easy to say that webclient is used. A declaration of the header information, a URL, and a post data are complete. I found a problem when I was happy. Before the post is all about string and other information, but next we need to post data and files at the same time. What should we do? How should we write the data in post? Google found such a post http://www.bkjia.com/kf/201203/123217.html, such a lot of posts, and most of the content is the same, transfer to each other. But the general central idea is to let us use stream concatenation for post, but to be honest, I haven't understood it for a long time. I'm too lazy to try and imitate it. Is there really no way to post files and data in the form of a = XXX1 & B = XXXX2 as before?
OK. Now the problem is solved. The conclusion is yes. In fact, the main reason why the data cannot be post as before is that the file stream and string cannot be spliced, you only need to change the file flow to a string and then OK. Continue to think about this idea.
If you have developed Flash, you should have a conclusion immediately, that is, base64. It happened that I used Base64 in a Flash project, so I quickly thought of this method. Microsoft's c # provides us with a very good Convert method. toBase64String, you can easily convert byte [] to the string type. With this method, you can splice and submit strings as before.
The request is displayed on the server, and then converted to byte [] using the built-in Convert. FromBase64String.
Finally, this is the result of the function of simultaneously posting data and files to the server.
Code on
Read the file and save it as byte []
FileStream fs = new FileStream ("file name", FileMode. Open, FileAccess. Read );
Byte [] byteFile = new byte [fs. Length];
Fs. Read (byteFile, 0, Convert. ToInt32 (fs. Length ));
Fs. Close ();
Concatenated string submitted
PostData = "id = xxx & name = xxx & file =" + HttpUtility. UrlEncode (Convert. ToBase64String (byteFile ));
The server receives information and saves it as a file.
String pic = Request ["file"]. ToString ();
FileStream fs = new FileStream ("full path of the saved file", FileMode. Create, FileAccess. Write );
Fs. Write (Convert. FromBase64String (pic), 0, Convert. FromBase64String (pic). Length );
Fs. Flush ();
Fs. Close ();
Now, it is really good to think about saving so much code. Let's say goodbye to the post content we found above.
From Yeju dongli