【问题标题】:Hot to upload image automaticaly after image preview to server图片预览后热自动上传图片到服务器
【发布时间】:2019-06-01 11:44:11
【问题描述】:

在 jquery 中成功预览图像到我的服务器后,我无法上传我的图像。它表明文件未在 form.append 语句或操作中定义。

我试图自己修复它,但找不到有效的解决方案。你能给我建议或帮助我一些代码。

function readURL(input) {
if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function(e) {
        $('#imagePreview').css('background-image', 'url('+e.target.result +')');
        $('#imagePreview').hide();
        $('#imagePreview').fadeIn(650);
    }
    reader.readAsDataURL(input.files[0]);
}
}
$("#imageUpload").change(function() {
readURL(this);

var formData = new FormData();
formData.append('formData', file);
$.ajax({
url: 'assets/uploadProfilepic.php',  //Server script to process data
type: 'POST',
data: formData,
contentType: false,
processData: false,
//Ajax events
success: function(html){
    alert(html);
}
});
});

HTML 部分

<div class="avatar-upload">
        <div class="avatar-edit">
            <input type='file' id="imageUpload" accept=".png, .jpg, .jpeg" name="file" />
            <label for="imageUpload"></label>
        </div>
        <div class="avatar-preview">
            <div id="imagePreview" style="background-image: url(http://i.pravatar.cc/500?img=7);">
            </div>
        </div>
    </div>

Uncaught ReferenceError: file is not defined but it should be or I don't really understand

请有人可以帮助我或提供解决方案。 感谢和问候

【问题讨论】:

    标签: javascript php jquery forms image-uploading


    【解决方案1】:

    file 变量在您的回调函数so it will use file from global scope 中没有定义值,其值为undefined。 在严格模式下,accessing a variable which has not been declared in local scope raises an error

    确保在您对readURL(this) 的调用下方,file 被分配给客户端发送的第一个文件(即this.files[0])。并使用FormDatas 附加文件:

    // The first argument ("file") is the POST key for the file
    // The file metadata can be retrieved using $_FILES['file']
    
    // The second argument is the file uploaded by the user
    // The third argument is the name of the file as perceived by the server
    var formData = new FormData();
    formData.append("file", file, "avatar.png");
    

    请记住,上传文件(包括头像),表单应该使用属性enctype="multipart/form-data",这样浏览器才能正确发送图像文件。

    实现文件上传还不是全部;建议您在服务器端验证文件(使用 PHP,您可以使用 mime_content_type 函数,该函数需要 fileinfo 扩展名)。在做任何事情之前,请阅读this page on POST file uploads

    【讨论】:

    • 谢谢你帮我用另一种方式完成了,我应该检查你的答案并关闭步骤还是写我的方法更简单?
    • 如果您发现或必须做一些可以提高浏览器兼容性/稳定性/安全性的事情,那么您可以查看我的答案以供参考。但是,如果您完成了,您可以将答案标记为已接受,因为这将帮助有同样问题的用户。
    猜你喜欢
    • 2019-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-06
    • 2011-06-01
    相关资源
    最近更新 更多