C # HTTP Series 11 ordinary file stream file upload remote server

One application operation is most commonly used to upload attachments, ASP.NET client is generally achieved by upload control,

<input type="file" id="fileUpload" runat="server" />

C # background in the following ways to save the file to your service

1 HttpFileCollection files = HttpContext.Current.Request.Files;
2 HttpPostedFile postedFile = files["fileUpload"];
3 postedFile.SaveAs(postedFile.FileName);

The above scenario is a simple management system and website is the most common way to upload files to the client's specified directory IIS server.

With the development and popularization of cloud applications, third-party application development platform or platform is deployed on a cloud server, such as Ali cloud, Tencent cloud, seven cattle cloud, Yun and so on. Large third-party open application platform is provided Restful API for developers to upload the calls (local or remote file) or download the business data for business development.

Upload the traditional control applications in the cloud application model does not apply for the attachment upload and download.

Provide a common post attachments in the following way:

. 1  ///  <Summary> 
2  ///   the data buffer (stream typically refers to a file or byte array corresponding to the memory stream) uploaded to the resource identified by the URI. (Body containing data)
 . 3  ///  </ Summary> 
. 4  ///  <param name = "URL"> request target the URL </ param> 
. 5  ///  <param name = "Data"> body data (byte data ) </ param> 
. 6  ///  <param name = "method"> request method. Use WebRequestMethods.Http enumeration value </ param> 
. 7  ///  <param name = "contentType"> <= langword See "the Content-type" /> value of the HTTP header. Please use the constant ContentType class to obtain. Default file application / OCTET-Stream </ param>
  
 9 public HttpResult UploadData(string url, byte[] data, string method = WebRequestMethods.Http.Post, string contentType = HttpContentType.APPLICATION_OCTET_STREAM)
10 {
11     HttpResult httpResult = new HttpResult();
12     HttpWebRequest httpWebRequest = null;
13 
14     try
15     {
16         httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
17         httpWebRequest.Method = method;
18         httpWebRequest.Headers = HeaderCollection;
19         httpWebRequest.CookieContainer = CookieContainer;
20         httpWebRequest.ContentLength = data.Length;
21         httpWebRequest.ContentType = contentType;
22         httpWebRequest.UserAgent = _userAgent;
23         httpWebRequest.AllowAutoRedirect = _allowAutoRedirect;
24         httpWebRequest.ServicePoint.Expect100Continue = false;
25 
26         if (data != null)
27         {
28             httpWebRequest.AllowWriteStreamBuffering = true;
29             using (Stream requestStream = httpWebRequest.GetRequestStream())
30             {
31                 requestStream.Write(data, 0, data.Length);
32                 requestStream.Flush();
33             }
34         }
35 
36         HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
37         if (httpWebResponse != null)
38         {
39             GetResponse(ref httpResult, httpWebResponse);
40             httpWebResponse.Close();
41         }
42     }
43     catch (WebException webException)
44     {
45         GetWebExceptionResponse(ref httpResult, webException);
46     }
47     catch (Exception ex)
48     {
49         GetExceptionResponse(ref httpResult, ex, method, contentType);
50     }
51     finally
52     {
53         if (httpWebRequest != null)
54         {
55             httpWebRequest.Abort();
56         }
57     }
58 
59     return httpResult;
60 }

With this method, derived with about 2 overloading manner:

Overload 1: upload files to a specified local resource with the specified URI. (Body containing data)

. 1  ///  <Summary> 
2  ///   specified upload files to the local resource with the specified URI. (Body containing data)
 . 3  ///  </ Summary> 
. 4  ///  <param name = "URL"> request target the URL </ param> 
. 5  ///  <param name = "fileFullName"> be uploaded files (containing fully qualified name of the full path) </ param> 
. 6  ///  <param name = "method"> request method. Use WebRequestMethods.Http enumeration value </ param> 
. 7  ///  <param name = "contentType"> <= langword See "the Content-type" /> value of the HTTP header. Please use the constant ContentType class to obtain. Default file application / OCTET-Stream </ param>
  
 9 public HttpResult UploadFile(string url, string fileFullName, string method = WebRequestMethods.Http.Post, string contentType = HttpContentType.APPLICATION_OCTET_STREAM)
10 {
11     HttpResult httpResult = new HttpResult();
12     if (!File.Exists(fileFullName))
13     {
14         httpResult.Status = HttpResult.STATUS_FAIL;
15 
16         httpResult.RefCode = (int)HttpStatusCode2.USER_FILE_NOT_EXISTS;
17         httpResult.RefText = HttpStatusCode2.USER_FILE_NOT_EXISTS.GetCustomAttributeDescription();
18     }
19     else
20     {
21         FileStream fileStream = new FileStream(fileFullName, FileMode.Open, FileAccess.Read);
22         byte[] data = fileStream.ToByteArray();
23         httpResult = UploadData(url, data, method, contentType);
24     }
25 
26     return httpResult;
27 }

Overload 2: stream object specified (generally refers to a file or memory stream flow) with the specified resource upload URI. (Body containing data)

. 1  ///  <Summary> 
2  ///   stream objects specified (generally refers to a file or memory stream flow) with the specified URI upload resource. (Body containing data)
 . 3  ///  </ Summary> 
. 4  ///  <param name = "URL"> request target the URL </ param> 
. 5  ///  <param name = "Stream"> generally refers to a stream file or memory stream </ param> 
. 6  ///  <param name = "method"> request method. Use WebRequestMethods.Http enumeration value </ param> 
. 7  ///  <param name = "contentType"> <= langword See "the Content-type" /> value of the HTTP header. Please use the constant ContentType class to obtain. Default file application / OCTET-Stream </ param>
  
 9 public HttpResult UploadStream(string url, Stream stream, string method = WebRequestMethods.Http.Post, string contentType = HttpContentType.APPLICATION_OCTET_STREAM)
10 {
11     HttpResult httpResult = new HttpResult();
12     if (stream == null)
13     {
14         httpResult.Status = HttpResult.STATUS_FAIL;
15 
16         httpResult.RefCode = (int)HttpStatusCode2.USER_STREAM_NULL;
17         httpResult.RefText = HttpStatusCode2.USER_STREAM_NULL.GetCustomAttributeDescription();
18     }
19     else
20     {
21         byte[] data = stream.ToByteArray();
22         httpResult = UploadData(url, data, method, contentType);
23     }
24 
25     return httpResult;
26 }

Which  UploadData ()  call the GetResponse (), GetWebExceptionResponse (), GetExceptionResponse () method

. 1  ///  <Summary> 
2  /// Get HTTP response message
 . 3  ///  </ Summary> 
. 4  ///  <param name = "httpResult"> about to be encapsulated HTTP request HttpResult variable function returns </ param> 
. 5  ///  <param name = "HttpWebResponse"> the HTTP response being read </ param> 
. 6  Private  void GetResponse ( REF httpResult httpResult, the HttpWebResponse HttpWebResponse)
 . 7  {
 . 8      httpResult.HttpWebResponse = HttpWebResponse;
 . 9      httpResult.Status = httpResult .STATUS_SUCCESS;
 10      httpResult.StatusDescription = httpWebResponse.StatusDescription;
11     httpResult.StatusCode = (int)httpWebResponse.StatusCode;
12 
13     if (ReadMode == ResponseReadMode.Binary)
14     {
15         int len = (int)httpWebResponse.ContentLength;
16         httpResult.Data = new byte[len];
17         int bytesLeft = len;
18         int bytesRead = 0;
19 
20         using (BinaryReader br = new BinaryReader(httpWebResponse.GetResponseStream()))
21         {
22             while (bytesLeft > 0)
23             {
24                 bytesRead = br.Read(httpResult.Data, len - bytesLeft, bytesLeft);
25                 bytesLeft -= bytesRead;
26             }
27         }
28     }
29     else
30     {
31         using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream()))
32         {
33             httpResult.Text = sr.ReadToEnd();
34         }
35     }
36 }
. 1  ///  <Summary> 
2  /// Raised when an error occurs during the acquisition HTTP access network information abnormal response
 . 3  ///  </ Summary> 
. 4  ///  <param name = "httpResult"> about to be encapsulated HTTP request function HttpResult variable return </ param> 
. 5  ///  <param name = "WebException"> exception object caused when an error occurs during access to the network </ param> 
. 6  Private  void GetWebExceptionResponse ( REF HttpResult httpResult, the WebException WebException)
 . 7  {
 . 8      the HttpWebResponse = webException.Response exResponse AS the HttpWebResponse;
 . 9      IF (exResponse!= null)
10     {
11         httpResult.HttpWebResponse = exResponse;
12         httpResult.Status = HttpResult.STATUS_FAIL;
13         httpResult.StatusDescription = exResponse.StatusDescription;
14         httpResult.StatusCode = (int)exResponse.StatusCode;
15 
16         httpResult.RefCode = httpResult.StatusCode;
17         using (StreamReader sr = new StreamReader(exResponse.GetResponseStream(), EncodingType))
18         {
19             httpResult.Text = sr.ReadToEnd();
20             httpResult.RefText = httpResult.Text;
21         }
22 
23         exResponse.Close();
24     }
25 }
///  <Summary> 
/// Gets the exception of the HTTP response information
 ///  </ Summary> 
///  <param name = "httpResult"> about to be encapsulated HTTP request HttpResult variable function returns </ param> 
///  <param name = "ex"> exception object </ param> 
///  <param name = "Method"> HTTP requests </ param> 
///  <param name = "contentType"> HTTP header type < / param> 
Private  void GetExceptionResponse ( REF httpResult httpResult, EX Exception, String Method, String contentType = "")
{
    contentType = string.IsNullOrWhiteSpace(contentType) ? string.Empty : "-" + contentType;
    StringBuilder sb = new StringBuilder();
    sb.AppendFormat("[{0}] [{1}] [HTTP-" + method + contentType + "] Error:  ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"), _userAgent);
    Exception exception = ex;
    while (exception != null)
    {
        sb.AppendLine(exception.Message + " ");
        exception = exception.InnerException;
    }
    sb.AppendLine();

    httpResult.HttpWebResponse = null;
    httpResult.Status = HttpResult.STATUS_FAIL;

    httpResult.RefCode = (int)HttpStatusCode2.USER_UNDEF;
    httpResult.RefText += sb.ToString();
}

 

Guess you like

Origin www.cnblogs.com/SavionZhang/p/11419532.html