通过Ajax上传图片

时间:2016-05-27 08:21:25

标签: php jquery ajax

那么事情是已经有一个编辑过的表单有很多字段但是所有的保存和验证都是通过ajax进行的。 他们现在问我要上传一个文件,我很难设置一个输入然后把它拿回去,但是因为所有这些都是ajax我不能。

我不想改变所有功能,如果没有必要,请通过提交。 我找了一些文件通过ajax上传,但所有这些都是类型拖放,我不喜欢它们,因为你只需要一个简单的文件。 我发现那些在flash中看起来很简单......

是否有任何简单的脚本允许我通过ajax上传一个简单的文件,而无需更改提交字段的类型。

提前感谢配偶;)

//the js that saves all the inputs
function _edit_campaign(){
var data = formvalues_inspinia("body");
data.action=_action;
data.status=$("#smf_ior_status").val();

$.ajax({
    url: "/save_changes",
    dataType: "json",
    data: data,
    method:"POST",
    success: function (response) {
        if(!response.status){
            toastr_error(response.desc);
            $( "#submit_confirm" ).prop( "disabled", false );
            $("#"+response.camp).focus();
        }else{
            toastr_success(response.desc);

        }
    }
});

}

2 个答案:

答案 0 :(得分:1)

客户端

$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST",             // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false,       // The content type used when sending data to the server.
cache: false,             // To unable request pages to be cached
processData:false,        // To send DOMDocument or non processed data file it is set to false
success: function(data)   // A function to be called if request succeeds
{

});

服务器端

$sourcePath = $_FILES['file']['tmp_name'];       // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ;    // Moving Uploaded file

答案 1 :(得分:1)

您可以使用" ajaxSubmit"以更简单的方式实现此目的。 在您的页面上包含jquery.form.js并提交表单。

 $(form).ajaxSubmit({
            url: url,
            type: "POST",           
            success: function (response) {
              // do what you need with response
        });

它会在服务器上发送包含文件的所有表单数据,然后您可以定期处理这些数据。

相关问题