【问题标题】:How to get the form file field in jquery to upload image如何在jquery中获取表单文件字段以上传图片
【发布时间】:2014-08-14 05:56:18
【问题描述】:

我有下面的html

This form allows you to upload a file to the server.<br>
        <div class="imguploadpath" style="width:100%;height:200px;background-color:#CCC;">
          <form name="myFormName" id ="myFormId" action="" method="post">
             <input type="file" name="img" id = "image_pe">
             <br/><br/><br/><br/>
             <input id="cmdSubmit" value="Submit" type="submit" class="">
          </form>
        </div>

我正在尝试使用以下脚本获取文件字段值以在 php 中上传文件

jQuery( "#cmdSubmit" ).on( "click", function() {
   var file = jQuery('#image_pe').val(); 

//我必须在 jquery ajax 中将文件属性发送到 php 文件

 $.ajax({
            url: 'submit.php?files',
            type: 'POST',
            data: data,
            cache: false,
            dataType: 'json',
            processData: false, // Don't process the files
            contentType: false, // Set content type to false as jQuery will tell the server its a query string request
            success: function(data, textStatus, jqXHR)
            {
                if(typeof data.error === 'undefined')
                {
                    // Success so call function to process the form
                    submitForm(event, data);
                }
                else
                {
                    // Handle errors here
                    console.log('ERRORS: ' + data.error);
                }
            },
            error: function(jqXHR, textStatus, errorThrown)
            {
                // Handle errors here
                console.log('ERRORS: ' + textStatus);
                // STOP LOADING SPINNER
            }
        });
       return false;

    });

但是var file 只返回一些临时路径c://fakepath/image.jpg

jquery和php怎么上传,需要在php文件中传表单域,我知道value()jquery函数出错了。

正确的做法是什么?

对于php文件上传,我正在考虑使用这个脚本http://www.tizag.com/phpT/fileupload.php

【问题讨论】:

标签: php jquery ajax file-upload


【解决方案1】:

试试这个: jQuery:

var formdata = new FormData();
            jQuery.each($('#image_pe')[0].files, function(i, file) {
             formdata.append('image_pe', file);
            });


            $.ajax({
                url: "/my.php",
                data : formdata,
                dataType : "json",
                type : "post",
                cache: false,
                contentType: false,
                processData: false,
                success: function(data){

                },
                failure: function(){
                    $(this).addClass("error");
                }
            });
            return false;

PHP 代码:

$file = $_FILES['image_pe'];

【讨论】:

  • 嗨,这解决了 jquery 问题,但你也可以添加 php 代码..谢谢
【解决方案2】:

检查这个。这可能对你很有帮助

http://malsup.com/jquery/form/#file-upload

【讨论】:

    猜你喜欢
    • 2011-03-17
    • 2011-07-21
    • 1970-01-01
    • 1970-01-01
    • 2011-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多