<%@ WebHandler Language="C#" Class="UploadHandler" %>
using System;
using System.Web;
using System.IO;
public class UploadHandler : System.Web.IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
Stream sr = context.Request.InputStream;
string filename = context.Request.QueryString["fileName"].ToString();
try
{
byte[] buffer = new byte[4096];
int bytesRead = 0;
using (FileStream fs = File.Create(context.Server.MapPath("ClientBin/" + filename + ".jpg"), 4096))
{
while ((bytesRead = sr.Read(buffer, 0, buffer.Length)) > 0)
{
fs.Write(buffer, 0, bytesRead);
}
}
}
catch (Exception e)
{
}
finally
{
sr.Dispose();
}
}
public bool IsReusable {
get {
return false;
}
}
}
private void ImportButton_Clicked(object sender, System.Windows.RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog()
{
Filter = "Jpeg Files (*.jpg)|*.jpg|All Files(*.*)|*.*",
Multiselect = true
};
if (openFileDialog.ShowDialog() == true)//.DialogResult.OK)
{
WebClient webclient = new WebClient();
foreach (FileInfo fi in openFileDialog.Files)
{
webclient.OpenWriteCompleted += new OpenWriteCompletedEventHandler(webclient_OpenWriteCompleted);
UriBuilder ub = new UriBuilder("http://localhost:52508/UploadHandler.ashx");
ub.Query = string.Format("fileName={0}", fi.Name);
webclient.OpenWriteAsync(ub.Uri, "POST", fi.OpenRead());
}
}
}
void webclient_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
{
System.Net.WebClient client = sender as System.Net.WebClient;
if (e.Cancelled != true)
{
Stream clientStream = e.UserState as Stream;
Stream serverStream = e.Result;
byte[] buffer = new byte[4096];
int count = 0;
while ((count = clientStream.Read(buffer, 0, buffer.Length)) > 0)
{
serverStream.Write(buffer, 0, count);
}
serverStream.Close();
clientStream.Close();
}
}
如果上傳超過4MB,記得在Web.config加上↓
- <httpRuntime maxRequestLength="51200"/>
如果不能上傳試試加上crossdomain.xml↓
- <?xml version="1.0"?>
- <!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
- <cross-domain-policy>
- <allow-http-request-headers-from domain="*" headers="*"/>
- </cross-domain-policy>