3

这可以作为正常形式正常工作:

<form id="frm1" enctype="multipart/form-data" action="form_handler_post.php" method="POST">
    <input type="hidden" name="MAX_FILE_SIZE" value="300000" />     
    Send this file: <input name="userfile" type="file" />
    <input type="text" name="theRefNum" />
    <input type="submit" value="Send File" />
</form>

...但我想使用 jQuery 发布表单的内容(即图像),因为我有很多其他数据要同时发布并且不想将其包含在与图片上传。例如

$.post("form_handler_post.php", { name: "John", time: "2pm", otherData: "Friday", image:#######});

我试过了image:userfileimage:'userfile'image:$('userfile').val()无济于事。

如何在数据部分包含图像文件 - 即如何访问图像value

4

3 回答 3

0

你不能通过使用普通的ajax来做到这一点。您必须使用一些可用的插件。大多数插件在后端使用 iframe。看到这个http://jquerybyexample.blogspot.com/2012/08/5-best-jquery-file-upload-plugin.html

于 2013-03-15T11:46:12.023 回答
0
$("input[name='userfile']").on("change", function(){
    readURL($(this).get(0));
})
function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('.somepicholder img').attr('src', e.target.result);
        }
        reader.readAsDataURL(input.files[0]);
    }
}
于 2013-03-15T11:48:05.127 回答
0

您需要将文件提交到 iframe,因为您无法在 jQuery 中通过 AJAX 提交文件:

$('#frm1 input[type="submit"]').click(function(e) {
    /* Prevent this from submitting the form */
    e.preventDefault();

    /* Create an iframe. */
    var iframeName = "iframe" + (new Date()).getTime(),
        iframe = $('<iframe id="' + iframeName  + '" name="' + iframeName  + '"></iframe>');

    /* Add the iframe to the page and hide it. */
    $(this).append(iframe);
    $(iframe).hide();

    /* Set the form's target to point to the iframe. */
    $(this).attr({
        "action": "mypage.ext",
        "method": "post",
        "enctype": "multipart/form-data",
        "encoding": "multipart/form-data",
        "target": iframeName  
    });

    /* Call the modified form's submit function. */
    $(this).submit();
})

此代码在页面上创建一个 iframe,并确保它具有唯一的 ID 和名称。然后它将表单提交到隐藏的 iframe。

然后,您可以使用 iframe 的onload函数回调父页面(前提是它位于同一域中)。使用类似window.parent.parentFunction("Successfully uploaded!").

于 2013-03-15T11:48:51.973 回答