from:https://www.cnblogs.com/refuge/p/8534847.htmlhtml
服務端接收文件流代碼:
public async Task<HttpResponseMessage> ReceiveFileByStream()
{
var stream = HttpContext.Current.Request.InputStream;
if (stream.Length > 0)
{
var absolutePath = HttpContext.Current.Request.MapPath("/img/");
if (!Directory.Exists(absolutePath))
{
Directory.CreateDirectory(absolutePath);
}
var fileType = "";
var bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
//前兩個字節表明文件類型,這裏以 JPG 類型爲例
var bs = bytes[0].ToString() + bytes[1].ToString();
if (bs.Equals("255216"))
{
fileType = ".jpg";
}
var path = absolutePath + Guid.NewGuid() + fileType;
await Task.Run(() =>
{
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
{
fs.Write(bytes, 0, bytes.Length);
}
});
return Request.CreateResponse(HttpStatusCode.OK, "上傳成功!");
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "沒有文件耶,哥們!");
}
}
客戶端上傳文件流代碼:
static string TestHttpClientUpload()
{
var resultStr = string.Empty;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://192.168.20.15:57895");
string apiUrl = "api/upload/ReceiveFileByStream";
string path = @"C:\Users\xxxx\Desktop\woman.jpg";
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
HttpContent content = new StreamContent(fs);
var result = client.PostAsync(apiUrl, content).Result;
fs.Dispose();
resultStr = result.Content.ReadAsStringAsync().Result;
return resultStr;//上傳成功
}
HttpWebRequest:api
static string TestHttpWebRequestUpload()
{
var resultStr = string.Empty;
string url = "http://192.168.20.15:57895/api/upload/ReceiveFileByStream";
HttpWebRequest request = WebRequest.CreateHttp(url);
request.Method = "post";
string path = @"C:\Users\xxxx\Desktop\woman.jpg";
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
var requestStream = request.GetRequestStream();
fs.CopyTo(requestStream);
fs.Dispose();
requestStream.Dispose();
var result = request.GetResponseAsync().Result;
var responseStream = result.GetResponseStream();
using (StreamReader sm = new StreamReader(responseStream))
{
resultStr = sm.ReadToEnd();
}
return resultStr;//上傳成功
}