0

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)

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

devpolo
  • 2,487
  • 3
  • 12
  • 28

2 Answers2

2

$_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");
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • There is nothing wrong with using a blob or along with fetch, and he isn't stringifing anything, it may just be a dummy blob, demonstration us currently how he uploads a file with fetch. i do think `file_get_contents` would be the right answer. – Endless Mar 07 '23 at 10:47
-4

If you are sending a file then "Content-Type" shouldn't be "text/plain".

Set Content-Type to "multipart/form-data".

{
    "Content-Type": 'multipart/form-data'
}
  • The body **isn't** multipart/form-data so that won't work. Even if it was, the content-type for `multipart/form-data` has a **mandatory** `boundary` parameter that you omitted. – Quentin Mar 07 '23 at 10:44