var rFilter = /^(image\/bmp|image\/gif|image\/jpeg|image\/png|image\/tiff)$/i; //控制格式ajax
var iMaxFilesize = 2097152; //控制大小2Msegmentfault
function preview(file) {api
var reader = new FileReader();app
if (!rFilter.test(file.type)) { 異步
alert("文件格式必須爲圖片"); ide
return; url
} spa
if (file.size > iMaxFilesize) {code
alert("圖片大小不能超過2M");regexp
return;
}
reader.onload = function(e) {
//圖片的base64格式,能夠直接當成img的src屬性
var $img = $('<img>').attr("src", e.target.result);
$(".preview").append($img);
//使用FormData
的最大優勢就是咱們能夠異步上傳一個二進制文件,在此用來上傳圖片
var formdata = new FormData();//建立一個formdata對象
//經過append(key, value)來添加數據,若是指定的key不存在則會新增一條數據,若是key存在,則添加到數據的末尾具體可看http://www.javashuo.com/article/p-tiovbwqw-ka.html
formdata.append("image",file.files[0]);
$.ajax({
url: "/s/api?cmd=Image.add&tip=video_banner",
type:"POST",
cache:false,
data:formdata,
processData:false, // 告訴jQuery不要去處理髮送的數據
contentType:false, // 告訴jQuery不要去設置Content-Type請求頭
success:function(data){
sign = data.res.sign;
}
});
};
reader.readAsDataURL(file);
}
$('[type=file]').change(function(e) {
var file = e.target.files[0];
preview(file);
});