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
{
request = null;
}
return result;
}
客户端调用方法:
var postUrl = "http://***/
WebglUploadFile.ashx";
NameValueCollection collection = new NameValueCollection
{
{"code", "b475831566d8e222faf1927bb8440905"},
{"unitid", "***"},
{"fileName", Path.GetFileName(img)}
};
HttpUploadFile(postUrl, img, "file", "image/jpeg", collection);
服务器端接收文件:
<%@ WebHandler Language="C#" Class="WebglUploadFile" %>
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web;
using BLL.Common;
using DAL.Access;
public class WebglUploadFile : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string dirPath = @"d:\pic\";
var code = context.Request.Form["code"];
var unitid = context.Request.Form["unitid"];
var fileName = context.Request.Form["fileName"];
if (code != "b475831566d8e222faf1927bb8440905") //自定义验证码,防止恶意上传
{
context.Response.ContentType = "text/plain";
context.Response.Write("对不起,参数错误");
context.Response.End();
}
if (unitid.Trim() == "")
{
context.Response.ContentType = "text/plain";
context.Response.Write("对不起,参数错误");
context.Response.End();
}
var param = new SqlParameter[1];
var i = 0;
param[i++] = new SqlParameter("@UnitID", SqlDbType.VarChar, 20) { Value = unitid };
if (SqlHelper.ExSql_ReturnValue("SELECT COUNT(*) FROM *** WHERE unitid=@UnitID", param, "U").ToInt32(0) > 0)
{
dirPath += unitid;
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
if (context.Request.Files.Count > 0)
{
var imgFile = context.Request.Files[0];
var name = HttpUtility.UrlDecode(fileName);
dirPath = dirPath.Combine(name);
imgFile.SaveAs(dirPath);
context.Response.ContentType = "text/plain";
context.Response.Write("true");
context.Response.End();
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
转载请注明原文地址: https://ju.6miu.com/read-3020.html