You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Sweet Alert 2+jQuery+PHP的文件上传功能故障排查求助

Fixing Sweet Alert 2 File Upload with jQuery & PHP

Let's walk through the issues in your code and fix them step by step:

Frontend (JavaScript) Issues & Fixes

Your main problem here is how you're adding the file to FormData—you're passing a file name string instead of the actual file object, plus an incorrect header setting that breaks the multipart form data.

Corrected JavaScript Code

$('#swal_upload').click(function(){
  var api = 'api/UploadFile.php';
  swal({
    title: "Carica immagine",
    html: '<input id="fileupload" type="file" name="userfile">'
  }).then(function() {
    var fileInput = $('#fileupload')[0];
    // Add a check to ensure a file was selected
    if (!fileInput.files.length) {
      swal('Errore', 'Seleziona un file prima di caricarlo!', 'error');
      return;
    }
    
    var formData = new FormData();
    // Append the actual file object, not just the file name
    formData.append('userfile', fileInput.files[0]);
    
    $.ajax({
      type: 'POST',
      url: api,
      data: formData,
      dataType: 'json',
      processData: false,
      contentType: false,
      // Remove the manual Content-Type header—jQuery handles this automatically
      // headers: {"Content-Type":"form-data"},
      async: true,
      success: function(result){
        console.log("OK client side");
        console.log(result.Response);
        // Show user feedback based on server response
        if (result.Response.uploaded === "Upload OK server side") {
          swal('Successo', 'File caricato correttamente!', 'success');
        } else {
          swal('Errore', result.Response.uploaded, 'error');
        }
      },
      error: function(xhr, status, error) {
        console.error('AJAX Error:', error);
        swal('Errore', 'Errore nella comunicazione con il server', 'error');
      }
    });
  })
});

Key Frontend Fixes:

  • Pass the file object: Use fileInput.files[0] instead of $('#fileupload').val() to get the actual file data for FormData.
  • Remove manual header: When processData and contentType are set to false, jQuery automatically sets the correct multipart/form-data header with the boundary identifier—manual setting breaks this.
  • Add validation: Check if a file was selected before sending the request to avoid unnecessary server calls.
  • Better error handling: Add an AJAX error callback and user-facing feedback for success/failure.

Backend (PHP) Issues & Fixes

Your PHP code has a typo in the $_FILES key, missing variable initialization, and lacks error handling for upload issues.

Corrected PHP Code (api/UploadFile.php)

<?php
$entered = "PHP started";
$tmpFilePath = null;
$newFilePath = null;
$uploaded = null;
$fileName = null;

// First, check if a file was uploaded without errors
if (isset($_FILES['userfile']) && $_FILES['userfile']['error'] === UPLOAD_ERR_OK) {
    $tmpFilePath = $_FILES['userfile']['tmp_name'];
    $fileName = basename($_FILES['userfile']['name']);
    $uploaddir = 'public/';
    
    // Ensure the upload directory exists and is writable
    if (!is_dir($uploaddir)) {
        // Create directory with recursive permissions
        mkdir($uploaddir, 0755, true);
    }
    
    if (is_writable($uploaddir)) {
        $newFilePath = $uploaddir . $fileName;
        if(move_uploaded_file($tmpFilePath, $newFilePath)) {
            $uploaded = "Upload OK server side";
        } else {
            $uploaded = "Upload failed server side: Could not move uploaded file";
        }
    } else {
        $uploaded = "Upload failed server side: Upload directory is not writable";
    }
} else {
    // Handle specific upload errors
    if (isset($_FILES['userfile'])) {
        switch($_FILES['userfile']['error']) {
            case UPLOAD_ERR_INI_SIZE:
                $uploaded = "Error: File exceeds server size limit";
                break;
            case UPLOAD_ERR_FORM_SIZE:
                $uploaded = "Error: File exceeds form size limit";
                break;
            case UPLOAD_ERR_NO_FILE:
                $uploaded = "Error: No file selected";
                break;
            default:
                $uploaded = "Upload error: Code " . $_FILES['userfile']['error'];
        }
    } else {
        $uploaded = "Error: No file received";
    }
}

// Prepare and send response
$array['Response'] = array(
    'entered' => $entered,
    'tmp_path' => $tmpFilePath,
    'new_path' => $newFilePath,
    'file_name' => $fileName,
    'uploaded' => $uploaded
);
echo json_encode($array);
?>

Key Backend Fixes:

  • Fix $_FILES key: Changed $_FILES['file']['name'] to $_FILES['userfile']['name'] to match your form input's name attribute.
  • Initialize variables: Set default values for all response variables to avoid undefined variable warnings.
  • Directory validation: Check if the public/ directory exists and is writable—this is a common cause of move_uploaded_file failures.
  • Detailed error handling: Add specific messages for different upload error codes to make debugging easier.

After applying these fixes, your file upload should work correctly. Test it by selecting a file and checking the public/ directory for the uploaded file, plus the console/alert feedback.

内容的提问来源于stack exchange,提问作者Luca Crippa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:32:49