<script type="text/javascript">
function upload() {
var file1 = document.getElementById("file1"); postFile(file1.files[0]);
} function postFile(data) {
//1.创建异步对象(小浏览器)
var req = new XMLHttpRequest(); //2.设置参数
req.open("post", "/API/ImgUp.ashx", true); //3.设置 请求 报文体 的 编码格式(设置为 表单默认编码格式)
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//4.设置回调函数
req.onreadystatechange = function () {
//请求状态readyState=4准备就绪,服务器返回的状态码status=200接收成功
if (req.readyState == 4 && req.status == 200) {
if (req.responseText != "error") {
//changeName(req.responseText);
$("#img").attr("src", req.responseText);
}
}
};
//4.发送异步请求
req.send(data);//post传参在此处
}
</script> <body> <input id="file1" type="file" value="选择文件" />
<input id="btnUp" onclick="upload()" type="button" value="上传" />
<img id="img" src="" /> </body>

后台ashx处理

        public void ProcessRequest(HttpContext context)
{
//context.Request["data"]
Stream stream = new BufferedStream(context.Request.InputStream);
byte[] buffer=new byte[stream.Length]; stream.Read(buffer, , buffer.Length);
string path = context.Server.MapPath("/ImgUp/") + "1.jpg"; File.WriteAllBytes(path, buffer); context.Response.Write("/ImgUp/1.jpg");
}

* 使用 ajaxfileupload.js 异步上传

     <script src="Scripts/jquery-2.1.4.min.js"></script>
<script src="Scripts/ajaxfileupload.js"></script>
<script type="text/javascript">
function upload2() {
$.ajaxFileUpload
(
{
url: '/API/ImgUp2.ashx', //用于文件上传的服务器端请求地址
secureuri: false, //是否需要安全协议,一般设置为false
fileElementId: 'file1', //文件上传域的ID
dataType: 'html', //返回值类型 一般设置为json
success: function (data, status) //服务器成功响应处理函数
{
alert("ok");
//$("#img1").attr("src", data.imgurl);
//if (typeof (data.error) != 'undefined') {
// if (data.error != '') {
// alert(data.error);
// } else {
// alert(data.msg);
// }
//}
},
error: function (data, status, e)//服务器响应失败处理函数
{
alert("error");
}
}
)
return false;
} </script> <body>
<form id="form1" >
<input id="file1" name="file1" type="file" value="选择文件" />
<input id="btnUp" onclick="upload2()" type="button" value="上传" />
<img id="img" src="" />
</form>
</body>
04-28 19:37