How to upload image to the local server externally?

2

I have a problem trying to upload a photo to my local server, everything works fine if I use an action and refer to the folder where my php file is, but it's not what I need because it redirects me to an empty page, I need to redirect myself to another html outside the server and save the image inside my folder on the local disk, I do not know if my JS file is wrong because apparently it can not execute.

PHP

<?php 
$tmp_name = $_FILES['img_up']["tmp_name"];
$name = $_FILES['img_up']["name"];
$nuevo_path="apkw/img/".$name;
move_uploaded_file($tmp_name,$nuevo_path);
?>

JS

$(document).ready(function() {

    read(0);

});

var host = "http://localhost:8080"; 

function read() {
    $.ajax({
        method: "POST",
        url: host + "/subir.php"

    }).done(function(data) {
        $("#nel").empty();
        if (data.length > 0) {
            var html = "";

            $.each(data, function(i) {
                console.log(data[i]);
                html += '';
            })
        }
    });
}

HTML

<!DOCTYPE html>
<html>
    <body>
        <form enctype="multipart/form-data" method="post">
            <input type="file" name="img_up">
            <input value="Subir" type="submit" >
        </form>
        <script type="text/javascript" src="js/prueba.js"></script>
    </body>
</html>
    
asked by Eiren Leza Caballero 05.04.2018 в 18:13
source

1 answer

1

I copied part of the solution from Raphael Schweikert in link

First you save the values of the form:

var fdata = new FormData();
$.each($('#file')[0].files, function(i, file) {
    fdata.append('file-'+i, file);
});

As we call the input by its id, you will have to add it:

<input id="file" type="file" name="img_up">

Then call with ajax:

$.ajax({
    url: host + "/subir.php",
    data: fdata,
    cache: false,
    contentType: false,
    processData: false,
    method: 'POST',
    type: 'POST',
}).done(function(data) {
    $("#nel").empty();
    if (data.length > 0) {
        var html = "";
        $.each(data, function(i) {
            console.log(data[i]);
            html += '';
        });
    }
});

In the PHP part, you will see the file in the variable:

$_FILES['file-0']

More or less like this:

<?php
    $tmp_name = $_FILES['file-0']["tmp_name"];
    $name = $_FILES['file-0']["name"];
    $nuevo_path="apkw/img/".$name;
    move_uploaded_file($tmp_name,$nuevo_path);
?>

Another alternative would be to use header to change the location on the blank screen:

header("Location: index.html");

In the latter case it would be added after move_uploaded_file ... and you would skip the whole part of posting the file by ajax.

    
answered by 05.04.2018 в 20:25