logo资料库

ASP.NET 上传图片到指定的图片服务器.doc

第1页 / 共4页
第2页 / 共4页
第3页 / 共4页
第4页 / 共4页
资料共4页,全文预览结束
ASP.NET 上传图片到指定的图片服务器 此实例是:从应用服务器将图片上传到图片服务器的某一个指定的 IIS 目录中 使用技术:WebClient、异步上传 流程: 1、在图片服务器上发布一个 IIS 的项目,项目中包含:图片存放目录、ASHX 文件 2、在应用服务器上发布一个 IIS 的项目上,上传图片功能 3、应用服务务点击图片,通过调用图片服务器上的 ASHX 文件,并使用 WEBCLIENT 异步方 式,将图片上传到图片服务器中指定的目录下 说明:这种方式的优点,均衡 IO 读取速度,分散数据存储,适用于图片较多的需求。
代码: 一、图片服务器端 添加一个“ashx”文件(就是“一般处理程序”) Cs 代码如下: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.IO; namespace ImageCenter { /// /// Handler1 的摘要说明 /// public class Handler1 : IHttpHandler { public void ProcessRequest(HttpContext context) { string filename = context.Request.QueryString["filename"].ToString(); //("Images/")为图片存储目录 using (FileStream inputStram = File.Create(context.Server.MapPath("Images/") + filename)) { } } SaveFile(context.Request.InputStream, inputStram); 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;
} 二、应用服务器端 HTML 代码: 在头部添加 Async="true" <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ImageUpdate.aspx.cs" Inherits="TEMP2010.ImageUpdate" Async="true" %>

CS 代码: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; using System.Net; namespace TEMP2010 { e) public partial class ImageUpdate : System.Web.UI.Page { MemoryStream ms; protected void Page_Load(object sender, EventArgs e){} protected void wc_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs { } int bufSize = 10; int byteGet = 0; byte[] buf = new byte[bufSize]; while ((byteGet = ms.Read(buf, 0, bufSize)) > 0)//循环读取,上传 { } e.Result.Write(buf, 0, byteGet);//注意这里 e.Result.Flush(); e.Result.Close();//关闭 ms.Close();//关闭ms
protected void Button1_Click(object sender, EventArgs e) { FileUpload fi = FileUpload1; byte[] bt = fi.FileBytes;//获取文件的Byte[] ms = new MemoryStream(bt);//用Byte[],实例化ms //("http://localhost:7910/Handler1.ashx")是图片服务器的ashx文件 UriBuilder url = new UriBuilder("http://localhost:7910/Handler1.ashx");//上 url.Query = string.Format("filename={0}", Path.GetFileName(fi.FileName));// 传路径 上传url参数 WebClient wc = new WebClient(); wc.OpenWriteCompleted += new OpenWriteCompletedEventHandler(wc_OpenWriteCompleted);//委托异步上传事件 wc.OpenWriteAsync(url.Uri);//开始异步上传 } } }
分享到:
收藏