Jquery異步上傳圖片


網頁中這樣:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1">
</head>
<title></title>
<script src="Scripts/jquery-1.8.2.min.js"></script>
<script type="text/javascript">
function uploadImage() {
//判斷是否有選擇上傳文件
var imgPath = $("#uploadFile").val();
if (imgPath == "") {
alert("請選擇上傳圖片!");
return;
}
//判斷上傳文件的后綴名
var strExtension = imgPath.substr(imgPath.lastIndexOf('.') + 1);
if (strExtension != 'jpg' && strExtension != 'gif'
&& strExtension != 'png' && strExtension != 'bmp') {
alert("請選擇圖片文件");
return;
}
$.ajax({
type: "POST",
url: "handler/UploadImageHandler.ashx",
data: { imgPath: $("#uploadFile").val() },
cache: false,
success: function (data) {
alert("上傳成功");
$("#imgDiv").empty();
$("#imgDiv").html(data);
$("#imgDiv").show();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("上傳失敗,請檢查網絡后重試");
}
});
}
</script>

<body>
<form enctype="multipart/form-data" method="post">
<input type="file" id="uploadFile" />
<input type="button" id="btnUpload" value="確定" onclick="uploadImage()" />
<div id="imgDiv">
</div>
</form>
</body>
</html>

 

 

 

 

一般處理程序中這樣:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace test
{
/// <summary>
/// UploadImageHandler 的摘要說明
/// </summary>
public class UploadImageHandler : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
//不知道為什么獲取不到
//HttpPostedFile file = context.Request.Files["userFile"];
string filePath = context.Request["imgPath"];
string path = "UploadImgs\\";
Bitmap map = new Bitmap(filePath);
string fileName = Path.GetFileName(filePath);
string mapPath = context.Server.MapPath("~");
string savePath = mapPath + "\\" + path + fileName;
map.Save(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;
}
}
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM