引言
在上一篇 jQuery + ashx 實現圖片按比例預覽、異步上傳及顯示 中核心是使用 HTML5 的 FileReader對象來實現。
但現在噁心的 IE 瀏覽器對HTML5支持太差,遂請教 google 大師,發現 juqey 中有個jquery.ajaxfileupload.js插件可實現無刷性上傳文件,
此插件的原理是在文檔中創建iframe和form,然後再將文件上傳到服務器進行處理,並異步返回信息到客戶端。
參考資料地址:
思路
代碼
function readURL(input) {
if ($.browser.msie && $(input).val() != "") {
// IE 中的input file 對象必須包含 runat="server" 標籤
var file_id = $(input).attr("id");
// 終於成功了,IE 中的input file 對象必須包含 runat="server" 標籤
$.ajaxFileUpload(
{
url: '../uploader.ashx',
secureuri: false,
fileElementId: file_id, //必須包含 runat="server" 標籤
dataType: 'text',
success: function (data, status) {
var base64 = $(data).text();
// $(input).parent().find("input[type=hidden]").val(base64);
$("#hf_base64").val(base64);
// var imgobj = $(input).parent().children("img");
var imgobj = $('#photo_img');
load_obj_base64(imgobj, base64);
},
error: function (data, status, e) {
// alert(status);
// alert(e);
}
});
}
else if (input.files && input.files[0]) {
var reader = new FileReader();
reader.readAsDataURL(input.files[0]);
var maxWidth = 200, maxHeight = 200;
reader.onload = function (e) {
var base64 = e.target.result;
$(input).parent().children("input[type=hidden]").val(base64);
var imgobj = $(input).parent().children("img");
load_obj_base64(imgobj, base64);
};
}
}
2.增加一個 uploader.ashx 處理 image 返回 base64
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
/// <summary>
/// uploader 的摘要說明
/// </summary>
public class uploader : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Charset = "utf-8";
try
{
HttpPostedFile file = context.Request.Files[0];
byte[] buffer = null;
string base64 = "data:image/jpeg;base64,";
if (file != null)
{
buffer = getByte(file);
base64 += Convert.ToBase64String(buffer);
}
//context.Response.Write(base64);
context.Response.Write(@base64);
}
catch (Exception ex)
{
context.Response.Write("0");
}
}
private byte[] getByte(HttpPostedFile file)
{
byte[] buffer = new byte[file.ContentLength];
file.InputStream.Read(buffer, 0, buffer.Length);
return buffer;
}
public bool IsReusable
{
get
{
return false;
}
}
}