简体   繁体   English

使用 ajax 和 php 从多个表单上传图像

[英]upload image from multiple form with ajax and php

in PHP page with multiple form tag to register user information.在 PHP 页面中使用多个表单标签来注册用户信息。 using ajax to collect data and post to register PHP page now i want to upload image to server folder but i failed.使用 ajax 收集数据并发布到注册 PHP 页面现在我想将图像上传到服务器文件夹但我失败了。

my html code:我的 html 代码:

<label for="upimage" class="btn btn-sm btn-primary mb-75 mr-75">Upload Image</label>
<input type="file" id="upimage" hidden accept="image/*" name="image"/>

Javascript Code: Javascript 代码:

let data1 = document.getElementById('data1').value,
    data2 = document.getElementById('data1').value,
    data3 = document.getElementById('data1').value,
    upimage = document.getElementById('upimage').value;
$.ajax({
    url:"././newregister.php",
    method:"POST",
    data:{action:'newregister', data1:data1, data2:data2,
        data3:data3, upimage:upimage},
    success:function(data){
        alert(data);
    }
});

newregister php code:新注册 php 代码:

$uploads_dir = './uploads';
if ($_FILES["file"]["error"] == UPLOAD_ERR_OK) {
    $tmp_name = $_FILES["file"]["tmp_name"];
    $name = $_FILES["file"]["name"];
    move_uploaded_file($tmp_name, "$uploads_dir/$name");
    echo "Sucsess"; 
}
else
{
    echo "Error" . $_FILES["file"]["error"] ; 
}

ERR: Undefined index: file in.... on line.... ERR:未定义的索引:文件在....在线....

Given by POST method uploads通过POST 方法上传

Be sure your file upload form has attribute enctype="multipart/form-data" otherwise the file upload will not work.确保您的文件上传表单具有属性 enctype="multipart/form-data" 否则文件上传将无法正常工作。

Your current solution lacks enctype, that's why your file is not getting uploaded to the server and therefore isn't in the superglobal variable $_FILES.您当前的解决方案缺少 enctype,这就是您的文件没有上传到服务器的原因,因此不在超全局变量 $_FILES 中。


As ferikeem already said.正如ferikeem已经说过的那样。 Wrap your data in a FormData Object and send it that way.将您的数据包装在 FormData Object 中并以这种方式发送。 See: https://stackoverflow.com/a/5976031/10887013请参阅: https://stackoverflow.com/a/5976031/10887013

JavaScript JavaScript

let fd = new FormData();
fd.append("you_file_key_here", $("#upimage")[0].files[0]);
fd.append("data1", $("#data1")[0].value);
fd.append("data2", $("#data2")[0].value);
fd.append("data3", $("#data3")[0].value);

$.ajax({
    url: "././newregister.php",
    method: "POST",
    data: fd,
    processData: false,
    contentType: false,
    success: function(data){
        alert(data);
    }
});

$_FILES["file"] , here is your problem. $_FILES["file"] ,这是你的问题。

In $_FILES array key "file" doesn't exists.$_FILES数组键"file"不存在。 As I see you need to change $_FILES["file"] with $_FILES["upimage"] .如我所见,您需要使用$_FILES["upimage"]更改$_FILES["file"] ] 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM