jquery 实现点击图片上传

html:
<img id="uploadImage" onclick='uploadImageFunction()' src="path_to_image.jpg" alt="Upload Image">



jquery:
function uploadImageFunction() {
    var fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.onchange = function() {
        // 处理用户选择的文件,例如读取文件内容并发送到服务器
        var file = fileInput.files[0];
        // ... 处理文件 ...
    
//验证文件格式
var allowedExtensions = /(\.png|\.jpg|\.jpeg|\.gif)$/i; // 定义允许的扩展名正则表达式

var formData = new FormData(); // 创建一个 FormData 对象
formData.append('file', file); // 将文件添加到 FormData 对象中

if (!allowedExtensions.exec(file.name)) {
alert('请上传PNG、JPG、JPEG或GIF格式的图片!');
return false; // 如果格式不正确,阻止后续操作
}
// ... 处理文件 ...
$.ajax({
url: '/fileInput', // 服务器端处理文件上传的脚本地址
type: 'POST',
data: formData,
processData: false, // 告诉 jQuery 不要处理发送的数据
contentType: false, // 告诉 jQuery 不要设置内容类型头信息
success: function(data) {
// 上传成功后的回调函数,data 是服务器返回的数据
console.log('上传成功');
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
// 上传失败后的回调函数,jqXHR 是 XMLHttpRequest 对象,textStatus 是请求状态,errorThrown 是异常信息
console.log('上传失败');
console.log(textStatus);
console.log(errorThrown);
}
});
}; fileInput.click(); // 模拟点击,打开文件选择对话框 }
posted @ 2024-04-13 14:11  祈愿仙帝  阅读(58)  评论(0编辑  收藏  举报