实现图上传简单功能
一、建立
1.建立一个项目,创建几个web应用程序
2.为web应用程序添加FileUpload何Upload文件夹连个文件夹保存文件和图片
二、添加文件
1.为FileUpload文件夹添加ImageUpload.ashx:业务处理
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplicationModle.FileUpload
{
/// <summary>
/// ImageUpload 的摘要说明
/// </summary>
public class ImageUpload : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
//context.Response.Write("Hello World");
HttpPostedFile file = context.Request.Files["imgFile"]; //通过Files 方法获得上传的图片
string path = "/upload/" +Guid.NewGuid().ToString()+ file.FileName; //建立图片保存的路径,为了保证不重复,通过拼接id实现:Guid.NewGuid().ToString()
file.SaveAs(context.Request.MapPath(path)); //通过SaveAs方法保存将图片保存到对应的路径地址中
//拼接前端代码,显示图片
string str = string.Format("<html><head></head><body><img src='{0}'/></body></html>", path);
context.Response.Write(str); //提交前端显示
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
2.为FileUpload文件夹 ImageUpload.html,显示界面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="ImageUpload.ashx" method="post" enctype="multipart/form-data">
<input type="file" name="imgFile"/>
<input type="submit" value="上传" />
</form>
</body>
</html>
三、运行
选择ImageUpload.html右键浏览器运行