Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Upload a blob file created using javascript to a php server

Javascript:

let myFile = new Blob(["A file"], { type: "text/plain"});
fetch("server_location.php", {
  method: "POST",
  body: myFile,
  headers: {
    "Content-Type": "text/plain"
  }).then((res) => { return res.text(); }.then((text) => { console.log(text) };

Php:

<?php
var_dump($_FILES)

Required
Should show the file in the file array
Output
array (0)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Please give me a solution so that I can upload custom text blob file created in javascript to my php server.

>Solution :

$_FILES is populated when you upload a request formatted as Multipart Form Data and labeled with the current content-type.

You are uploading a blob labelled as plain text, and stringifed (probably to [object Object]).


To send a multipart request, use a FormData object.

const myFile = new Blob(["A file"], { type: "text/plain"});
const data = new FormData();
data.append("myFile", myFile, "filename.txt");
fetch("server_location.php", {
    method: "POST",
    body: data,
})

To send plain text and read it:

  • Don’t use a blob
  • Do read from STDIN
fetch("server_location.php", {
    method: "POST",
    body: "a plain text string",
    headers: { "Content-Type": "text/plain" }
})

and

$data = file_get_contents("php://input");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading