using System.IO;
using System.Windows.Media.Imaging;
using System.Text;
namespace fileup
{
public partial class MainPage : UserControl
{
OpenFileDialog openfile = new OpenFileDialog();
public MainPage()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
//openfile.Filter = "Jpeg Files (*.jpg)|*.jpg";//限制文件类型为图片
openfile.Multiselect = false;//不允许多选
if (openfile.ShowDialog() == true)
{
if (openfile.File != null)
{
//BitmapImage bmp = new BitmapImage();
//bmp.SetSource(openfile.File.OpenRead());
//image1.Source = bmp;
WebClient webclient = new WebClient();
Uri uri = new Uri("http://localhost:51594/upload.ashx?name=" + openfile.File.Name, UriKind.RelativeOrAbsolute);
webclient.OpenWriteAsync(uri, "POST", openfile.File.OpenRead());
webclient.Headers["Content-Type"] = "multipart/form-data";
webclient.OpenWriteCompleted += new OpenWriteCompletedEventHandler(webclient_OpenWriteCompleted);
}
else
{
MessageBox.Show("请选择图片!");
}
}
}
void webclient_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
{
Stream stream = e.UserState as Stream;
Stream serverStream = e.Result;
byte[] buffer = new byte[4096];
int readcount = 0;
// 将需要上传的流读取到指定的字节数组中
while ((readcount = stream.Read(buffer, 0, buffer.Length)) > 0)
{
// 将指定的字节数组写入到目标地址的流
serverStream.Write(buffer, 0, readcount);
}
serverStream.Close();
stream.Close();
MessageBox.Show("上传成功!");
}
}
}上面两句标记为红色的部分不是太理解,为什么要把上传的数据流读取到e.result()转化的流中,还有把数据传到Hander.ashx处理程序的原理?
用silverlight??用js简单多了,如uploadify等,sl不懂
uploadify 不也是用 flash,silverlight 等技术做的。
LZ把标记为红色的部分的代码去掉,看下有什么影响就知道。