1. [代码]本地上传
/*本地上传*/
/*
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="upload_index" %>
*/
using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Web;
public partial class upload_index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string action = Request.QueryString["action"];
if (action == "save")
{
Response.ContentType = "text/html;charset=utf-8";
Response.Write("");
HttpFileCollection HFC = Request.Files;
for (int i = 0; i < HFC.Count; i++)
{
HttpPostedFile currentFile = HFC[i];
TransportFile(currentFile);
}
}
}
private void TransportFile(HttpPostedFile File)
{
Stream s = File.InputStream;
byte[] byts = new byte[s.Length];
s.Read(byts, 0, byts.Length);
s.Close();
s.Dispose();
if (File.FileName.LastIndexOf(".") >= 0)
{
Random ra = new Random();
string nowFileName = DateTime.Now.Subtract(new DateTime(2000, 1, 1)).TotalMilliseconds.ToString().Replace(".", "") + ra.Next() + File.FileName.Substring(File.FileName.LastIndexOf("."));
NameValueCollection NVC = System.Configuration.ConfigurationManager.AppSettings;
for (int i = 0; i < NVC.Count; i++)
{
if (NVC.Keys[i].IndexOf("upload") == 0)
{
PostFile(NVC[i], byts, nowFileName);
}
}
Response.Write("
图片地址:" + System.Configuration.ConfigurationManager.AppSettings["imgurlprev"].ToString() + nowFileName + "
");
}
}
private void PostFile(string url,byte[] data,string fileName)
{
string pwd = System.Configuration.ConfigurationManager.AppSettings["imgserverpwd"].ToString();
HttpWebRequest HRQ = (HttpWebRequest)System.Net.WebRequest.Create(url + "?filename=" + fileName + "&p=" + pwd);
HRQ.Method = "POST";
HRQ.KeepAlive = false;
HRQ.ContentType = "multipart/form-data";
HRQ.Timeout = 10 * 1000;
HRQ.ContentLength = data.Length;
Stream sr = HRQ.GetRequestStream();
sr.Write(data, 0, data.Length);
HttpWebResponse RES = (HttpWebResponse)HRQ.GetResponse();
if (HRQ.HaveResponse)
{
Stream Rs = RES.GetResponseStream();
StreamReader RsRead = new StreamReader(Rs);
Response.Write(RsRead.ReadToEnd());
}
else
{
Response.Write("
" + url + ":失败
");
}
sr.Close();
sr.Dispose();
}
}
2. [代码]接收端
<%@ Page Language="C#" AutoEventWireup="true" %>
<%
string p = Request.QueryString["p"];
string pwd = System.Configuration.ConfigurationManager.AppSettings["imgserverpwd"].ToString();
if (p == pwd)
{
string FolderPath = Server.MapPath("/files");
string filename = Request.QueryString["filename"];
System.IO.Stream stream = Request.InputStream;
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, (int)stream.Length);
Random ra = new Random();
string nowFilePath = FolderPath + "/" + filename;
System.IO.File.WriteAllBytes(nowFilePath, buffer);
Response.Write("
" + HttpContext.Current.Request.Url.Host + " " + filename + ":上传成功
");
}
%>