douguanya4248 2013-08-22 16:19
浏览 13
已采纳

在更改文件输入时上传文件

I am trying to upload a file on change of file input but I can't get it to work because I am not so good with javascript.

I did search on google and found this: How can I upload files asynchronously?

I used it and tried to change it to how I want to use it. But I am getting the error

`Uncaught TypeError: Illegal invocation`

This is my function:

function uploadFile(formData){
    $.ajax({
        url: 'inc/ajax/uploadFile.php',  //Server script to process data
        type: 'POST',
        data: {'formData':formData},
        //Ajax events
        success: function(html){
            alert(html);
        }
    });
}

I call the function like this:

$("input:file").change(function(){
    var file = this.files[0];
    uploadFile(file);
})

And uploadFile.php

<?php
 $formData = $_GET['formData'];
 echo $formData;
?>

I am just testing and trying to return the file in php to see if I can get it to work. But I have no idea on how I have to call it in PHP or send it with AJAX. I know how to upload it with PHP once I can retrieve the $_FILES in PHP.

  • 写回答

2条回答 默认 最新

  • dongyou2305 2013-08-22 16:30
    关注

    In addition to the other answer, add this to your ajax

    contentType: false,
    processData: false
    

    like:

    var formData = new FormData();
    formData.append('formData', file);
    $.ajax({
        url: 'inc/ajax/uploadFile.php',  //Server script to process data
        type: 'POST',
        data: formData,
        contentType: false,
        processData: false,
        //Ajax events
        success: function(html){
            alert(html);
        }
    });
    

    You should also think about people that may not have a newer browser, and just put a little error message, like:

    if(window.FormData === undefined){
        alert('sorry buddy you\'re browsers too old!');
        return;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 Keil编译时报错"no source": Error: #5: cannot open source
  • ¥50 操作系统时间无法更新
  • ¥20 Windows11, usb转hdmi,外接显示器无反应
  • ¥20 怎么在JavaFx的TableView中动态地添加数据。
  • ¥15 MFC里的工具栏按钮图标使用外部图片
  • ¥15 如何在 llama.cpp 服务器中实现用户登录功能的优化方案?(语言-c++)
  • ¥15 有会用octave 的吗,急!代做!好偿!
  • ¥15 有一套同城小程序源码,Uniapp前端,php+html+mysql后端 ,能不能教我搭建起来可以运行,我不知道怎样操作
  • ¥15 mac调用java.io接口无法在根目录生成文件
  • ¥15 java微服务节点假死,网关路由时长延迟