英文:
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
应该在文件数组中显示文件
Output
array (0)
请提供一个解决方案,以便我可以将在JavaScript中创建的自定义文本Blob文件上传到我的PHP服务器。
英文:
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.
答案1
得分: 2
$_FILES
是在上传一个以多部分表单数据格式的请求时填充的,并且带有当前的内容类型标签。
您正在上传一个标记为纯文本的 blob,并进行字符串化(可能为 [object Object]
)。
要发送一个多部分请求,请使用 FormData 对象。
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,
})
要发送纯文本并进行读取:
- 不要使用 blob
- 从 STDIN 读取
fetch("server_location.php", {
method: "POST",
body: "a plain text string",
headers: { "Content-Type": "text/plain" }
})
以及
$data = file_get_contents("php://input");
英文:
$_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");
答案2
得分: -4
如果您正在发送文件,则“Content-Type”不应为“text/plain”。
将Content-Type设置为“multipart/form-data”。
{
"Content-Type": 'multipart/form-data'
}
英文:
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'
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论