(通常處理程序)javascript
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string filePath = "";
string msg = "";
string fileNewName = "";
string result = string.Empty; //也是定義一個空變量
string fileNewPath = string.Empty;
//接收文件
HttpFileCollection files = context.Request.Files;
//判斷是否獲取到文件
if (files.Count > 0)
{
//設置圖片名稱
//DateTime.Now.ToString("yyyyMMddHHmmssff")
fileNewName = Guid.NewGuid() + "_" + Path.GetFileName(files[0].FileName);
//保存文件
files[0].SaveAs(context.Server.MapPath("~/Upload/" + fileNewName));
msg = "圖片上傳成功";
fileNewPath = "Upload/" + fileNewName;
result = "{msg:'" + msg + "',fileNewPath:'" + fileNewPath + "'}"
}
else
{
msg = "圖片上傳失敗";
result = "{msg:'" + msg + "'}";
}
context.Response.Write(result);
context.Response.End();
}html
<script type="text/javascript">
$(function () {
$(".file").on("change", "input[type='file']", function () {
var filePath = $(this).val();
//設置上傳文件的類型
if (filePath.indexOf("xls") != -1 || filePath.indexOf("xlsx") != -1 || filePath.indexOf("jpg") != -1) {
alert(111);
//執行上傳文件的操做
$.ajaxFileUpload({
url: "UploadHandler.ashx", // 請求地址
secureuri: false, // 是否開啓安全提交,默認爲false
fileElementId: "btnfile", //須要上傳的文件域的ID 也就是 <input type="file" id="btnfile" name="btnfile" />裏面的id
dataType: "json", //制定返回數據類型(json,html,xml,script) 若是不寫,jquery會自動判斷
success: function (data) { //執行成功以後自動執行的函數
console.log(data);
alert(data.msg);
$("#txt_filepath").val(data.fileNewPath);
$("#hImg").prop("src", data.fileNewPath);
},
error: function (data) { //執行失敗以後自動執行的函數
console.log(data);
}
})
}
else {
alert("請選擇正確格式的文件");
}
})
})
</script>java
<form id="form1" runat="server">
<div>
<span>選擇文件:</span>
<input type="text" readonly="readonly" id="txt_filepath" />
<a class="file">
<input type="file" id="btnfile" name="btnfile" />
瀏覽文件
</a>
<img style="width: 300px; height: 300px;" id="hImg" />
</div>jquery