Skip to content
Advertisement

Problem with link to file, javascript, xml, object FormData

I have a function that allows you to select an attachment, but I can’t get the file paths from it to send it to php.

Can it be done without using forms and reloading the entire page?

I update my function, but they return: from=s@p.pl&temat=da&msg=da&usser=lalala&file=[object FormData]

What I can do with it? I need link to file.

Function like this:

function create_form(){
var add= document.createElement("div");
add.id = "form";

var file = document.createElement("input");
file.type = "file";
file.id = "file";

var btn = document.createElement("button");
btn.id = "send";
btn.setAttribute("onclick", "send_email()");

add.appendChild(file);
add.appendChild(btn);
placeholder.appendChild(add);}

function send_email(){
php(url, params);
Function to comunication with php:

async function php(name, params, ofset){
var params = params;

if(document.getElementById("file")){
var plik = document.getElementById("file");
var file = plik.files[0];
var fd = new FormData();
fd.append("file", file);
params += '&file=' + fd;}

let http = XML();
let odp = "420 - error php function";

if(typeof ofset == 'undefined'){
var ofset = 100;}

http.onreadystatechange=function(){
if (http.readyState==4 && http.status==200)
{
odp = JSON.parse(this.responseText);
}}
var url = name;

http.open('POST', url, true);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

http.send(params)   

let promise = new Promise((resolve, reject) => {setTimeout(() => resolve(odp), ofset)});

let result = await promise;
return result;}

Advertisement

Answer

It looks to me like you’re using FormData incorrectly here. If you take a look at this part of your code:

var fd = new FormData();
fd.append("file", file);
params += '&file=' + fd;

Unless you serialize them somehow, binary files can’t be uploaded as URL parameters, they have to be sent as part of the request body. I think you’re close, and there’s just two changes you need to make here:

First, your URL parameters need to be tacked onto the URL itself:

var url = `${name}?${params}`;

You then need to pass your FormData into send():

var fd = new FormData();
fd.append("file", file);
}
...
http.send(fd);

If you need some more help using FormData, check the MDN docs.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement