其实上篇文章(看这里:http://blog.csdn.net/highplayer/article/details/7392337),只是一个伪上传,因为传递给后台的只是一个图片的URL,在本地测试可以通过,但真正部署在服务器上的时候就不行了。比如你传给服务器一个:C:\Documents and Settings\Administrator\桌面\A.jpg,服务器会在它本地电脑上的路径:C:\Documents and Settings\Administrator\桌面\A中找图片A,这怎么可能嘛。所以,上次的实现方式就是一个失败的例子。
百度了很久,终于让我发现了一个jQuery插件:ajaxupload.js。 这边有示例:http://www.phpletter.com/Demo/AjaxFileUpload-Demo/
靠这个插件,终于实现了真正的AJAX异步上传图片。
其实就个插件的原理就是构建一个form,然后用POST的方式提交整个Form。在后台中,通过传递来的Form,得到HttpPostedFile,在获取其中的图片信息,这样就实现后台上传图片了。
一个简单的DEMO。
前台:
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.3.1.min.js" type="text/javascript"></script>
<script src="Scripts/ajaxfileupload.js" type="text/javascript"></script>
<script type="text/javascript">
function ajaxFileUpload() {
$.ajaxFileUpload
(
{
url: 'handler/UploadImageHandler.ashx?userid=1&name=abc',
secureuri: false,
fileElementId: 'fileToUpload',
dataType: 'html',
beforeSend: function() {
$("#loading").show();
},
complete: function() {
$("#loading").hide();
},
success: function(data, status) {
if (typeof (data.error) != 'undefined') {
if (data.error != '') {
alert(data.error);
} else {
alert(data.msg);
}
}
},
error: function(data, status, e) {
alert(e);
}
}
)
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<table cellpadding="0" cellspacing="0" class="tableForm">
<thead>
<tr>
<th>
Ajax File Upload
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input id="fileToUpload" type="file" size="45" name="fileToUpload" class="input">
</td>
</tr>
<tr>
<td>
Please select a file and click Upload button
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<button class="button" id="buttonUpload" οnclick="return ajaxFileUpload();">
Upload</button>
</td>
</tr>
</tfoot>
</table>
</form>
</body>
后台,其实和上次差不多。代码:
public class UploadImageHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
//获取前台的FILE
HttpPostedFile file = context.Request.Files["fileToUpload"];
string path = "UploadImgs\\";
//Bitmap map = new Bitmap(filePath);
string fileName = Path.GetFileName(file.FileName);
string mapPath = context.Server.MapPath("~");
string savePath = mapPath + "\\" + path + fileName;
//map.Save(savePath);
file.SaveAs(savePath);
//上传成功后显示IMG文件
StringBuilder sb = new StringBuilder();
sb.Append("<img id=\"imgUpload\" src=\""+path.Replace("\\","/")+fileName+"\" />");
context.Response.Write(sb.ToString());
context.Response.End();
}
public bool IsReusable {
get {
return false;
}
}
}