[英]Post Error while upload file from form using JS and PHP
我想使用 JS 和 PHP 从表单上传文件。 但是当我发送文件时,我收到 POST 错误。
我的表单(HTML):
<input type="file" class="custom-file-input" id="file" multiple name="file"
onchange="readURL()"/>
脚本(JS):
function readURL() {
var files = document.getElementById("file").files;
if (files.length > 0) {
var formData = new FormData();
formData.append("file", files[0]);
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "send.php", true);
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var response = this.responseText;
if (response == 1) {
console.log("Upload successfully.");
}else{
console.log("File not uploaded.");
}
}
};
xhttp.send(formData);
}else{
console.log("Please select a file");
}
}
send.php 文件 (PHP)
if(isset($_FILES['file']['name'])){
// file name
$filename = $_FILES['file']['name'];
$location = 'js/'.$filename;
$file_extension = pathinfo($location, PATHINFO_EXTENSION);
$file_extension = strtolower($file_extension);
$valid_ext = array("pdf","doc","docx","jpg","png","jpeg");
$response = 0;
if(in_array($file_extension,$valid_ext)){
if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
$response = 1;
}
}
echo $response;
exit;
在控制台我得到错误:
PS文件send.php在主目录下,路径没问题
我找到了一个解决方案,对于要提供的静态文件,我必须配置中间件以将静态文件添加到管道中。
启动文件
public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles();
}
可以在此网站上找到有关此问题的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.