asp.net异步上传文件到多台服务器

 负载均衡多台服务器,内部服务器无法开端口上传文件,就用httpwebRequest访问内部ip进行上传文件的操作

 主机上传程序

/// <summary>
/// 保存文件,返回保存的文件名
/// </summary>
/// <param name="PostedFile"></param>
/// <returns></returns>
public string GetName(HttpPostedFile PostedFile, string savePath, List<string> extension,bool isfileName=false)
{
if (PostedFile.ContentLength == 0)
{
return "";
}
string Ret = "";
string CurrentPath = HttpContext.Current.Server.MapPath(savePath);
string FilePath = PostedFile.FileName;
string ExtensionName = Path.GetFileName(FilePath);
string[] ex = ExtensionName.Split('.');
ExtensionName = ex[ex.Length - 1].ToLower();
if (extension.Count > 0)
{
if (!extension.Contains(ExtensionName))
{
string Str = "";
extension.ForEach(x => Str += "," + x);
HttpContext.Current.Response.Write("<script>alert('附件上传失败,格式错误,支持" + Str + "');</script>");
return "";
}
}
ExtensionName = "." + ExtensionName;
string TimeNow = DateTime.Now.ToString("yyyyMMddHHmmfffff");
if (isfileName)
{
ExtensionName = FilePath;
}
else
{
ExtensionName = TimeNow + ExtensionName;
}

if (Directory.Exists(CurrentPath) == false)
{
Directory.CreateDirectory(CurrentPath);
}
string SaveFilePath = Path.Combine(CurrentPath, ExtensionName);
Random r = new Random();
while (File.Exists(SaveFilePath) == true)
{
File.Delete(SaveFilePath);
//ExtensionName = r.Next(1000) + ExtensionName;
//SaveFilePath = Path.Combine(CurrentPath, ExtensionName);
}
try
{
Ret = Path.GetFileName(SaveFilePath);
PostedFile.SaveAs(SaveFilePath);
//同步上传文件到其他远程分平台上
UploadFile(PostedFile.InputStream, savePath, ExtensionName);
}
catch
{
Ret = "";
}
return Ret;
}

/// <summary>
/// HttpContext.Current.Request.Files 文件上传文件到异地服务器
/// </summary>
/// <param name="savePath"></param>
/// <param name="extension">扩展名限制类型</param>
/// <returns></returns>
public string UpLoadFileGetName(string filename, Stream file_Stream, string filePath, List<string> extension, bool isfileName = false)
{
if (file_Stream.Length == 0)
{
return "";
}
string fujian = "";


string ExtensionName = "";
string file_name = Path.GetFileName(filename);
string[] ex = file_name.Split('.');
ExtensionName = ex[ex.Length - 1].ToLower();
if (extension.Count > 0)
{
if (!extension.Contains(ExtensionName))
{
string Str = "";
extension.ForEach(x => Str += "," + x);
HttpContext.Current.Response.Write("<script>alert('附件上传失败,格式错误,支持" + Str + "');</script>");
return " ";
}
}


string TimeNow = DateTime.Now.ToString("yyyyMMddHHmmfffff");
if (!isfileName)
{
file_name =TimeNow +"."+ ExtensionName;
}

try
{
UploadFile(file_Stream,filePath,filename);

fujian = filename;

}
catch(Exception e)
{
fujian = "";
}


return fujian;
}

 

 

 

/// <summary>
/// httpWebRequest上传文件到远程服务器上
/// </summary>
/// <param name="strRequestUri"></param>
/// <param name="file_Stream"></param>
/// <param name="strCookie">保存路径</param>
/// <param name="filename">文件名称</param>
private void UploadFile( Stream file_Stream, string strCookie, string filename)
{
//本地
//string[] list = { "http://192.168.1.16:5677//httpRequestupload.ashx", "http://192.168.1.16:5678//httpRequestupload.ashx", "http://192.168.1.16:5679//httpRequestupload.ashx", "http://192.168.1.16:5677//httpRequestupload.ashx" };
//远程
string[] list = { "http://10.0.20.49:80//httpRequestupload.ashx", "http://10.0.20.52:80//httpRequestupload.ashx", "http://10.0.20.50:80//httpRequestupload.ashx", "http://10.0.20.51:80//httpRequestupload.ashx" };

// 初始化HttpWebRequest
HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(list[0]);
HttpWebRequest httpRequest1 = (HttpWebRequest)HttpWebRequest.Create(list[1]);
HttpWebRequest httpRequest2 = (HttpWebRequest)HttpWebRequest.Create(list[2]);
HttpWebRequest httpRequest3 = (HttpWebRequest)HttpWebRequest.Create(list[3]);

// 封装Cookie
//UriBuilder url = new UriBuilder(strRequestUri);//上传路径
//url.Query = string.Format("filename={0}&path={1}", Path.GetFileName(filename), filePath);//上传url参数
Uri uri = new Uri(list[0]);
Uri uri1 = new Uri(list[1]);
Uri uri2 = new Uri(list[2]);
Uri uri3 = new Uri(list[3]);
//Cookie cookie = new Cookie("filename", Path.GetFileName(filename));
Cookie cookie2 = new Cookie("path", strCookie);

CookieContainer cookies = new CookieContainer();
//cookies.Add(uri, cookie);
cookies.Add(uri, cookie2);
cookies.Add(uri1, cookie2);
cookies.Add(uri2, cookie2);
cookies.Add(uri3, cookie2);
httpRequest.CookieContainer = cookies;
httpRequest1.CookieContainer = cookies;
httpRequest2.CookieContainer = cookies;
httpRequest3.CookieContainer = cookies;

// 生成时间戳
string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
byte[] boundaryBytes = Encoding.ASCII.GetBytes(string.Format("\r\n--{0}--\r\n", strBoundary));

// 填报文类型
httpRequest.Method = "Post";
httpRequest.Timeout = 1000 * 120;
httpRequest.ContentType = "multipart/form-data; boundary=" + strBoundary;
httpRequest1.Method = "Post";
httpRequest1.Timeout = 1000 * 120;
httpRequest1.ContentType = "multipart/form-data; boundary=" + strBoundary;
httpRequest2.Method = "Post";
httpRequest2.Timeout = 1000 * 120;
httpRequest2.ContentType = "multipart/form-data; boundary=" + strBoundary;
httpRequest3.Method = "Post";
httpRequest3.Timeout = 1000 * 120;
httpRequest3.ContentType = "multipart/form-data; boundary=" + strBoundary;

// 封装HTTP报文头的流
StringBuilder sb = new StringBuilder();
sb.Append("--");
sb.Append(strBoundary);
sb.Append(Environment.NewLine);
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append("file");
sb.Append("\"; filename=\"");
sb.Append(filename);
sb.Append("\"");
sb.Append(Environment.NewLine);
sb.Append("Content-Type: ");
sb.Append("multipart/form-data;");
sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine);
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sb.ToString());

// 计算报文长度
long length = postHeaderBytes.Length + file_Stream.Length + boundaryBytes.Length;
httpRequest.ContentLength = length;
httpRequest1.ContentLength = length;
httpRequest2.ContentLength = length;
httpRequest3.ContentLength = length;

// 将报文头写入流
Stream requestStream = httpRequest.GetRequestStream();
requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
Stream requestStream1 = httpRequest1.GetRequestStream();
requestStream1.Write(postHeaderBytes, 0, postHeaderBytes.Length);
Stream requestStream2 = httpRequest2.GetRequestStream();
requestStream2.Write(postHeaderBytes, 0, postHeaderBytes.Length);
Stream requestStream3 = httpRequest3.GetRequestStream();
requestStream3.Write(postHeaderBytes, 0, postHeaderBytes.Length);

// 将上传文件内容写入流 //每次上传4k 1024*4
byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)file_Stream.Length))];
int bytesRead = 0;

while ((bytesRead = file_Stream.Read(buffer, 0, buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
requestStream1.Write(buffer, 0, bytesRead);
requestStream2.Write(buffer, 0, bytesRead);
requestStream3.Write(buffer, 0, bytesRead);
}

// 将报文尾部写入流
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
// 关闭流
requestStream.Close();
// 将报文尾部写入流
requestStream1.Write(boundaryBytes, 0, boundaryBytes.Length);
// 关闭流
requestStream1.Close();
// 将报文尾部写入流
requestStream2.Write(boundaryBytes, 0, boundaryBytes.Length);
// 关闭流
requestStream2.Close();
// 将报文尾部写入流
requestStream3.Write(boundaryBytes, 0, boundaryBytes.Length);
// 关闭流
requestStream3.Close();
}

 

/// <summary>
/// 删除远程文件
/// </summary>
/// <param name="file_Stream"></param>
/// <param name="strCookie"></param>
/// <param name="filename"></param>
public void DeleteAsynFile( string filePath)
{
//本地
//string url = "http://192.168.1.16:5677//Deletefile.ashx";
//远程
string url = "http://10.0.20.49:80//Deletefile.ashx";
Uri uri = new Uri(url + "?path=" + filePath);
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";
            request.AllowAutoRedirect = false;
            request.Timeout = 5000;
            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            StreamReader readStream = new StreamReader(responseStream, System.Text.Encoding.UTF8);
            string retext = readStream.ReadToEnd().ToString();
            readStream.Close();

}

 

内部服务器接收文件程序

<%@ webhandler Language="C#" class="Upload_file2" %>

/**
* KindEditor ASP.NET
*
* 本ASP.NET程序是演示程序,建议不要直接在实际项目中使用。
* 如果您确定直接使用本程序,使用之前请仔细确认相关安全设置。
*
*/

using System;
using System.Collections;
using System.Web;
using System.IO;
using System.Globalization;
using LitJson;

public class Upload_file2 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//文件保存目录路径
String savePath = context.Request.QueryString["path"].ToString();
String dirPath = context.Server.MapPath("~/UpFiles/" + savePath+"/");
//文件保存目录URL
//String saveUrl = aspxUrl + "../../../../../../UpFiles/Editor/";
string saveUrl = "http://192.168.1.16:5678/UpFiles/Course/";
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
string filename = context.Request.QueryString["filename"].ToString();
string filePath=Path.Combine(dirPath, filename);
while (File.Exists(filePath) == true)
{
File.Delete(filePath);
}
using (FileStream inputStram = File.Create(filePath))
{
SaveFile(context.Request.InputStream, inputStram);

//context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
//context.Response.Write(saveUrl + filename);
//context.Response.End();
}

}
protected void SaveFile(Stream stream, FileStream inputStream)
{
int bufSize = 1024;
int byteGet = 0;
byte[] buf = new byte[bufSize];
while ((byteGet = stream.Read(buf, 0, bufSize)) > 0)
{
inputStream.Write(buf, 0, byteGet);
}
}
public bool IsReusable
{
get
{
return false;
}
}
}

 

转载于:https://www.cnblogs.com/wq555/p/11474427.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值