douyi3307 2018-01-17 14:13
浏览 117
已采纳

Sweet Alert 2使用php上传jQuery文件

I'm trying to create a file uploader inside a Sweet Alert 2 modal with jQuery and php. Here's my code, but it isn't working: how can I get this working?

Thank you

HTML (the button to open the modal with Sweet Alert 2):

<button class="bx--btn bx--btn--primary" type="button" id="swal_upload">Apri</button>

JavaScript:

$('#swal_upload').click(function(){
    var api = 'api/UploadFile.php';
    swal({
        title: "Carica immagine",
        html: '<input id="fileupload" type="file" name="userfile">'
    }).then(function() {
        var formData = new FormData();
        formData.append('userfile', $('#fileupload').val().replace(/.*(\/|\\)/, ''));
        console.log(formData);
        $.ajax({
          type: 'POST',
          url: api,
          data: formData,
          dataType: 'json',
          processData: false,
          contentType: false,
          headers: {"Content-Type":"form-data"},
          async: true,
          success: function(result){
            console.log("OK client side");
            console.log(result.Response);
          }
        });
    })
  });

php (api/UploadFile.php):

$entered = "PHP started";

$tmpFilePath = $_FILES['userfile']['tmp_name'];

$uploaddir = 'public/';

  if ($tmpFilePath != ""){
    $newFilePath = $uploaddir . basename($_FILES['userfile']['name']);

    if(move_uploaded_file($tmpFilePath, $newFilePath)) {
      $uploaded = "Upload OK server side";
    } else {
      $uploaded = "Upload failed server side";
    }
  }

  // Prepare response, close connection and send response to front-end
  $array['Response'] = array(
    'entered' => $entered,
    'tmp_path' => $tmpFilePath,
    'new_path' => $newFilePath,
    'file_name' => $_FILES['file']['name'],
    'uploaded' => $uploaded
  );

  echo json_encode($array);

The output I have in the console is:

FormData {}proto: FormData OK client side {entered: "PHP started", tmp_path: null, new_path: null, file_name: null, uploaded: null} entered:"PHP started" file_name:null new_path:null tmp_path:null uploaded:null proto:Object

As you can see the php starts, but no file is passed to the server.

  • 写回答

1条回答 默认 最新

  • doumei8258 2019-02-01 14:21
    关注

    I have used a solution based on the input file type from Sweetalert 2 and the FileReader/FormData objects from the view side. When you use an input file type of Sweetalert, an input element with the swal2-file css class will be created: enter image description here

    Then you can use the Sweetalert event onBeforeOpen to read the file data through the FileReader object. Finally you can send the file using ajax request with the FormData object. This would be the js source:

    $('#swal_upload').click(function() {
         Swal({
            title: 'Select a file',
            showCancelButton: true,
            confirmButtonText: 'Upload',
            input: 'file',
            onBeforeOpen: () => {
                $(".swal2-file").change(function () {
                    var reader = new FileReader();
                    reader.readAsDataURL(this.files[0]);
                });
            }
        }).then((file) => {
            if (file.value) {
                var formData = new FormData();
                var file = $('.swal2-file')[0].files[0];
                formData.append("fileToUpload", file);
                $.ajax({
                    headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
                    method: 'post',
                    url: '/file/upload',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function (resp) {
                        Swal('Uploaded', 'Your file have been uploaded', 'success');
                    },
                    error: function() {
                        Swal({ type: 'error', title: 'Oops...', text: 'Something went wrong!' })
                    }
                })
            }
        })
    })
    

    From the server side, using Laravel Php framework, you can get the file through a function like this:

    public function uploadFile(Request $request)
    {
        if ($request->hasFile('fileToUpload')) {
            $file_name = $request->file('fileToUpload')->getClientOriginalName();
            $earn_proof = $request->file('fileToUpload')->storeAs("public/files/", $file_name);
        }
    
        return response()->json(['result' => true], 200);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问如何在matlab里使用raven工具?
  • ¥100 关于ios手游充值到一定金额,再点充值提示公众号的问题。
  • ¥15 求一个stm32串口控制程序
  • ¥20 Windows 驱动开发版本疑问相关
  • ¥15 MAC 未能打开磁盘映像
  • ¥15 fastcap使用,二维导体输入问题
  • ¥15 hosts修改后不能访问
  • ¥15 关于化学反应速率C++编译问题/FLUENT
  • ¥20 Yolov5训练报错
  • ¥15 Unity发布gzip压缩的webgl之后让浏览器可以正常显示画面