文章分类

相关文章

WebRequest同时Post提交图片和字段信息

分类:ASP.NET-MVC     发布:2017-03-08     来源:本站     浏览:1309 次

1.封装好的方法:

public string HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection collection)
    {
        var result = string.Empty;
        var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
        var boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

        var request = (HttpWebRequest)WebRequest.Create(url);
        request.ContentType = "multipart/form-data; boundary=" + boundary;
        request.Method = "POST";
        request.KeepAlive = true;
        request.Credentials = CredentialCache.DefaultCredentials;

        var stream = request.GetRequestStream();
        var template = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
        foreach (string key in collection.Keys)
        {
            stream.Write(boundarybytes, 0, boundarybytes.Length);
            var formitem = string.Format(template, key, collection[key]);
            var formitembytes = Encoding.UTF8.GetBytes(formitem);
            stream.Write(formitembytes, 0, formitembytes.Length);
        }
        stream.Write(boundarybytes, 0, boundarybytes.Length);

        var headerTemplate ="Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
        var header = string.Format(headerTemplate, paramName, file, contentType);
        var headerbytes = Encoding.UTF8.GetBytes(header);
        stream.Write(headerbytes, 0, headerbytes.Length);

        var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
        var buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            stream.Write(buffer, 0, bytesRead);
        }
        fileStream.Close();

        var bytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
        stream.Write(bytes, 0, bytes.Length);
        stream.Close();

        WebResponse wresp = null;
        try
        {
            wresp = request.GetResponse();
            var stream2 = wresp.GetResponseStream();
            var reader2 = new StreamReader(stream2);
            result = reader2.ReadToEnd();
        }
        catch (Exception ex)
        {
            if (wresp != null)
            {
                wresp.Close();
                wresp = null;
            }
        }
        finally
  &nb

上一篇:程序员的工作究竟有多复杂?

下一篇:利用Rar压缩文件并FTP上传