Untitled.png
Javascript上傳一個文件或者圖片
$('input[name=image]').click(function(){
// 注意第一個[0]
var blobFile = $(this)[0].files[0];
// FormData對象
var fd = new FormData();
// 這里的"image"就是在服務器上獲取的時候的名字
// 例如PHP的話,$_FILE['image']就可以獲取到
fd.append("image", blobFile);
// 判斷文件大小,單位是byte
if (blobFile.size >= 1024 * 1024 * 10 || blobFile.size < 1024 * 10) {
return false;
}
//
$.ajax({
url: "/api/v2/post/img",
type: "POST",
data: fd,
processData: false,
contentType: false,
// contentType設置為false,默認是www-xxxxx
dataType: 'json',
success: function (res) {
if (res.errcode == 0) {
// 在caret所在處插入
var name;
var start = $("#p_ctt")[0].selectionStart,
end = $("#p_ctt")[0].selectionEnd;
if (start == end) name = 'image_' + parseInt(Math.random() * 100);
else name = $('#p_ctt').val().substring(start, end);
var new_content = $('#p_ctt').val().substring(0, start) + "\n) + ")\n" + $('#p_ctt').val().substring(end + 1);
$('#p_ctt').val(new_content);
}
},
error: function (jqXHR, textStatus, errorMessage) {
console.log(errorMessage);
}
});
});