如何使用ajax显示上传的图像?

时间:2014-02-06 05:25:40

标签: javascript php jquery html ajax

我需要上传图片并显示该图片而不重新加载页面如何实现这一点。我想我们可以使用Ajax表单提交来做到这一点。我尝试了以下代码,但Ajax表单提交功能不起作用。这段代码中有没有错误告诉我如何实现这个

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> 
        <script src="http://malsup.github.com/jquery.form.js"></script> 
        <script type="text/javascript">
            $(document).ready(function()
            {
              $('#myForm').ajaxForm(function()
                 { 
                    alert("Thank you for your comment!"); 
                }); 

            });
    </script>

    <body>
        <form id="myForm" action="" method="post"> 
          <input type="file" name="image_name" id="image_name" >
       </form>
    </body>

谢谢: - )

3 个答案:

答案 0 :(得分:2)

使用uploadify插件做这样的事情,我这样做通过ajax上传图片,将文件上传到uploadAllComlete函数设置图片tage src到url,文件通过上传存储在服务器上,你就完成了:< / p>

 <input type="file" name="fileUpload" value="" id="fileInput1" /> 
                 <p><a href="javascript:$('#fileInput1').uploadifyUpload();">Upload Files</a></p>

这是javascript函数:

<script type="text/javascript">


    $("#fileInput1").uploadify({
        'uploader': '@Url.Content("~/Scripts/jquery.uploadify-v2.1.4/uploadify.swf")',
        'script': '@Url.Content("~/Resource/Upload")',
        'auto': false,
        'multi': false,
        'expressInstall': '@Url.Content("~/Scripts/jquery.uploadify-v2.1.4/expressInstall.swf")',
        'cancelImg': '@Url.Content("~/Scripts/jquery.uploadify-v2.1.4/cancel.png")',
        'scriptAccess': 'always',
        'hideButton': false,
        'fileTypeDesc': 'Image Files',
        'fileTypeExts': ' *.jpg; *.png',
        'fileDataName': 'uploadedFile',
        'sizeLimit': 1000000000,
        'onError': function (event, ID, fileObj, errorObj) {
            $('#UploadedPicture').val('');
            $('#uploadedImage').attr('src', '');
            $('#uploadedImage').hide();
            //alert("name: " + fileObj.name + " error type: " + errorObj.type + ", info: " + errorObj.info);
        },
        'onAllComplete': function (event, data) {
            //alert("allcomplete => " + data.filesUploaded + ":" + data.errors + ":" + data.allBytesLoaded + ":" + data.speed);
        },
        'onCheck': function () {
            //alert("oncheck");
        },
        'onComplete': function (event, id, fileObj, response, data) {

            //alert("oncomplete => " + ":" + fileObj.name + ":" + fileObj.filePath + ":" + fileObj.size + ":" + response);
            $('#fileInput2').val(fileObj.name);
            $('#uploadedImage').attr('src', '/uploads/' + fileObj.name);


        },
        'onOpen': function (event, id, fileObj) {
            //alert("onopen => " + ":" + fileObj.name + ":" + fileObj.filePath + ":" + fileObj.size);
            var temp = fileObj.name.split('(');
            var filename = $.trim(temp[0]);
            $('#UploadedPicture').val('~/uploads/' + filename);
            $('#uploadedImage').attr('src', '/uploads/' + filename);
            $('#uploadedImage').show();
        },
        'onProgress': function (event, id, fileObj, data) {
            //alert("onprogress => " + ":" + fileObj.name + ":" + fileObj.filePath + ":" + fileObj.size + ":" + data.percentage + ":" + data.bytesLoaded + ":" + data.allBytesLoaded + ":" + data.speed);
        },
        'onUploadSuccess': function (file, data, response) { alert('test'); $('#fileInput2').val(file.name); },
        'onUploadComplete': function (file) {
            //alert('The file ' + file.name + ' finished processing.');
        },
        'onCancel': function (file) {
            $('#UploadedPicture').val('');
            $('#uploadedImage').attr('src', '');
            $('#uploadedImage').hide();
        }
    });

    </script>

这是我发布文件的服务器端功能:

public ActionResult Upload(HttpPostedFileBase uploadedFile)
        {
            if (uploadedFile.ContentLength == 0) return new EmptyResult();

            string[] temp = uploadedFile.FileName.Split('(');
            string FileName = temp[0].Trim();
            string savedFileName = Path.Combine(HttpContext.Server.MapPath("~/Uploads"), uploadedFile.FileName);
            uploadedFile.SaveAs(savedFileName);

            return new EmptyResult();
        }

答案 1 :(得分:1)

由于您使用的是JQuery表单插件,因此您将能够发送图像。您的代码是正确的,但有一些小错误。

你必须调用ajaxForm的submit方法来进行ajax调用,你需要在AjaxForm的完整事件中添加一个回调。(这里,我添加了事件onchange,这样,只有当用户选择一个图像,然后将触发ajax调用。)

这有效 -

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> 
<script src="http://malsup.github.com/jquery.form.js"></script> 
<script type="text/javascript">
$(document).ready(function(){
    //Added an onchange event.
    $("#image_name").on('change',function(){
        $("#myForm").ajaxForm(
            {complete:  function(data){
                             alert("Thank you for your comment!");
                        }
            }
        ).submit();
    });
});
</script>

<body>
    <form id="myForm" action="a.php" method="post">
        <input type="file" name="image_name" id="image_name" >
    </form>
</body>

答案 2 :(得分:0)

我使用它来使用ajax上传图像

$(document).ready(function() {
    var f = $('form');
    var l = $('#loader'); // loder.gif image
    var b = $('#button'); // upload button
    var p = $('#preview'); // preview area

    b.click(function(){
        // implement with ajaxForm Plugin
        f.ajaxForm({
            beforeSend: function(){
                l.show();
                b.attr('disabled', 'disabled');
                p.fadeOut();
            },
            success: function(e){
                l.hide();
                f.resetForm();
                b.removeAttr('disabled');
                p.html(e).fadeIn();
            },
            error: function(e){
                b.removeAttr('disabled');
                p.html(e).fadeIn();
            }
        });
    });
});