简体   繁体   中英

Post Error while upload file from form using JS and PHP

I want to upload file from form using JS and PHP. But when i send file, i got POST error.

My form (HTML):

    <input type="file" class="custom-file-input" id="file" multiple name="file" 
          onchange="readURL()"/>

Script (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 file (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;

In console i got error:

在此处输入图片说明

PS File send.php is located in main directory and path is ok

I found a sollution, for static files to be served, i must configure the Middleware to add static files to the pipeline.

Startup.cs

public void Configure(IApplicationBuilder app)
{
 app.UseStaticFiles();
}

More about this issue can be found on this website

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM