求一段JS或Jquery异步上传图片的代码

JavaScript08

求一段JS或Jquery异步上传图片的代码,第1张

图片和文件等流媒体 上传都是靠from表单的提交。

你可以设置一个隐藏的from表单

里面有个<input id='file' type='file'>

选择玩图片之后赋值给file

然后用jquery from表单提交即可

<form id="form" runat="server" enctype="multipart/form-data" >

<input id='file' type='file'>

</from> $.ajax({

    url:'XXXX',//上传后台路径

    data:$('#form').serialize(),

    type:"POST",

    success:function(){

    

    }

})

如果只是上传的话那太容易了,如果还要显示那就难了,因为要显示的话就不能只向服务器提交一次请求,必须异步提交。下面的例子是我亲自写的,异步提交上传图片并预览。全部代码都在。

首先建一个html文件,复制以下html文本。使用说明:

引用jquery两个js文件,网上自己搜吧,到处都有。

<script src="jquery-1.4.2.min.js" type="text/javascript"></script>

  <script src="jquery.form.js" type="text/javascript"></script>

2.添加两个文本框,第一个ID必须是“bigImage1”,第二个必须是“smallbigImage1”。

<input type="text" name="url1" id="bigImage1" style="width:150px" onclick="selectImage(this)" />

  <input type="hidden" name="smallUrl1" id="smallbigImage1" value="" />

当点击第一个文本框时,弹出一个上传窗口,选择一张图片并点“上传”,上传成功后可预览图片。此过程会在服务器上把原图片生成一张缩略图,并把原图URL和缩略图URL一起以JSON格式返回到前台页面,临时显示缩略图。当点击“确定”时,它会把两个URL添加到两个对应ID的文本框。第二个框是隐藏的,给用户的感觉就像是只返回一个URL一样。

3.请自己写脚本[document.getElementById("bigImage1").value] 获得两个文本框的值,再进行你想做的操作。

4.id为"uploadDiv"的DIV是一个整体,不可分割。主要是提供一个文件类型的表单,用于异步上传。请修改action的URL为你上传的后台路径。

下面是HTML代码

<!DOCTYPE html>

<html>

<head>

    <title>Index</title>

    <script src="jquery-1.4.2.min.js" type="text/javascript"></script>

    <script src="jquery.form.js" type="text/javascript"></script>

    <script type="text/javascript">

        function selectImage(obj) {

            var inputId = obj.id

            document.getElementById('btnSure').setAttribute('inputId', inputId)

            var x = window.event.x

            var y = window.event.y

            var uploadDiv = document.getElementById('uploadDiv')

            uploadDiv.style.left = x + 10 + 'px'

            uploadDiv.style.top = y + 10 + 'px'

            uploadDiv.style.position = 'fixed'

            uploadDiv.style.display = 'inline'

        }

        function closeDiv() {

            document.getElementById('btnSure').style.display = 'none'

            document.getElementById('showImage').style.display = 'none'

            document.getElementById('uploadDiv').style.display = 'none'

        }

        function makeSure(obj) {

            var inputId = obj.getAttribute('inputId')

            document.getElementById(inputId).value = document.getElementById('showImage').getAttribute('big')

            document.getElementById('small' + inputId).value = document.getElementById('showImage').getAttribute('small')

            document.getElementById('image' + inputId).src = document.getElementById('showImage').getAttribute('small')

            document.getElementById("btnSure").style.display = 'none'

            document.getElementById('showImage').style.display = 'none'

            document.getElementById('uploadDiv').style.display = 'none'

        }

        $(function () {

            //异步上传图片

            $('#btnUpload').click(function () {

                if ($('#upImage').val() == '') {

                    alert('请选择一张图片文件')

                    return

                }

                $('#fileForm').ajaxSubmit({

                    success: function (msg) {

                        var strJSON = msg //得到的JSON

                        var image = eval("(" + strJSON + ")") //转换后的JSON对象

                        document.getElementById('uploading').style.display = 'none'

                        $('#showImage').css('display', 'inline')

                        $('#showImage').attr('src', image.big)

                        $('#showImage').attr('big', image.big)

                        $('#showImage').attr('small', image.small)

                        $('#btnSure').css('display', 'inline')

                    }

                })

                document.getElementById('uploading').style.display = 'block'

            })

        })

    </script>

</head>

<body>

    

<p>上传单个文件或图片</p>

<div>

    <input type="text" name="url1" id="bigImage1" style="width:150px" onclick="selectImage(this)" />

    <input type="hidden" name="smallUrl1" id="smallbigImage1" value="" /> 

</div>

<div id="uploadDiv" style="width: 400px height: 280px border: 1px solid #9eb9f1

    background-color: #e1eaea text-align:left display:none z-index:999">

    <div>

        <div style="width: 376px float: left padding-left:4px padding-top:4px padding-bottom:4px overflow:hidden">

            <form id="fileForm" method="post" action="/Home/UploadImage" enctype="multipart/form-data" >

                <input type="file" id="upImage" name="upImage" style="padding-bottom: 1px padding-left: 8px

                    padding-right: 8px height: 24px width:220px padding-top: 1px" />

                <input type="button" id="btnUpload" value="上传" style="padding-bottom: 1px padding-left: 8px padding-right: 8px

                    height: 24px cursor: pointer padding-top: 1px line-height: 12px" />

                <span id="uploading" style="color:#ff0000 display:none font-size:14px font-weight:bold">上传中......</span>

                <input type="button" id="btnSure" value="确定" style="padding-bottom: 1px padding-left: 8px padding-right: 8px

                height: 24px cursor: pointer padding-top: 1px line-height: 12px display:none background-color:#9fd0f9" onclick="makeSure(this)" />

            </form>

        </div>

        <div style="width: 20px height: 30px float: right ">

            <div style="width: 20px height: 20px background-color:#9fc0f7 font-size:20px text-align:center line-height:16px cursor:pointer" onclick="closeDiv()">X</div>

        </div>

    </div>

    <div style="width:398px height:240px text-align:center overflow:hidden ">

        <img id="showImage" alt="预览图片" src="" style="width: 340px display:none" />

    </div>

</div>

</body>

</html>

下面是后台代码

返回到前台页面的JSON格式对象是以类的对象。

    public class ReturnImage

    {

        public string big { get set }

        public string small { get set }

        public string isSuccessfull { get set }

        public string message { get set }

    }

对于上传和生成缩略图,请自行完成,以下是ASP.NET MVC的例子。

    public class HomeController : Controller

    {

        //

        // GET: /Home/

        public ActionResult Index()

        {

            return View()

        }

        /// <summary>

        /// 上传图片

        /// </summary>

        /// <returns></returns>

        public ActionResult UploadImage()

        {

            //定义错误消息

            JsonResult msg = new JsonResult()

            try

            {

                //接受上传文件

                HttpPostedFileBase postFile = Request.Files["upImage"]

                if (postFile != null)

                {

                    DateTime time = DateTime.Now

                    //获取上传目录 转换为物理路径

                    string uploadPath = Server.MapPath("~/UploadFiles/" + time.Year + "/" + time.ToString("yyyyMMdd") + "/")

                    //文件名

                    string fileName = time.ToString("yyyyMMddHHmmssfff")

                    //后缀名称

                    string filetrype = System.IO.Path.GetExtension(postFile.FileName)

                    //获取文件大小

                    long contentLength = postFile.ContentLength

                    //文件不能大于2M

                    if (contentLength <= 1024 * 2048)

                    {

                        //如果不存在path目录

                        if (!Directory.Exists(uploadPath))

                        {

                            //那么就创建它

                            Directory.CreateDirectory(uploadPath)

                        }

                        //保存文件的物理路径

                        string saveFile = uploadPath + fileName + "_big" + filetrype

                        try

                        {

                            //保存文件

                            postFile.SaveAs(saveFile)

                            //保存缩略图的物理路径

                            string small = uploadPath + fileName + "_small" + filetrype

                            MakeThumbnail(saveFile, small, 320, 240, "W")

                            ReturnImage image = new ReturnImage()

                            image.big = "/UploadFiles/" + time.Year + "/" + time.ToString("yyyyMMdd") + "/" + fileName + "_big" + filetrype

                            image.small = "/UploadFiles/" + time.Year + "/" + time.ToString("yyyyMMdd") + "/" + fileName + "_small" + filetrype

                            msg = Json(image)

                        }

                        catch

                        {

                            msg = Json("上传失败")

                        }

                    }

                    else

                    {

                        msg = Json("文件大小超过限制要求")

                    }

                }

                else

                {

                    msg = Json("请选择文件")

                }

            }

            catch (Exception e)

            {

                

            }

            msg.ContentType = "text/html"

            return msg

        }

        /// <summary>

        

        由于回答超过最大限制,/// 生成缩略图 的代码请向我索取

Web Uploader 项目,符合你的要求。

1、引入资源

使用Web Uploader文件上传需要引入三种资源:JS, CSS, SWF。

<!--引入CSS-->

<link rel="stylesheet" type="text/css" href="webuploader文件夹/webuploader.css">

<!--引入JS-->

<script type="text/javascript" src="webuploader文件夹/webuploader.js"></script>

<!--SWF在初始化的时候指定,在后面将展示-->

2、Html

首先需要准备一个按钮,和一个用来存放添加的文件信息列表的容器。

<!--dom结构部分-->

<div id="uploader-demo">

    <!--用来存放item-->

    <div id="fileList" class="uploader-list"></div>

    <div id="filePicker">选择图片</div>

</div>

3、Javascript

创建Web Uploader实例

// 初始化Web Uploader

var uploader = WebUploader.create({

    // 选完文件后,是否自动上传。

    auto: true,

    // swf文件路径

    swf: BASE_URL + '/js/Uploader.swf',

    // 文件接收服务端。

    server: 'http://webuploader.duapp.com/server/fileupload.php',

    // 选择文件的按钮。可选。

    // 内部根据当前运行是创建,可能是input元素,也可能是flash.

    pick: '#filePicker',

    // 只允许选择图片文件。

    accept: {

        title: 'Images',

        extensions: 'gif,jpg,jpeg,bmp,png',

        mimeTypes: 'image/*'

    }

})

监听fileQueued事件,通过uploader.makeThumb来创建图片预览图。

PS: 这里得到的是Data URL数据,IE6、IE7不支持直接预览。可以借助FLASH或者服务端来完成预览。

// 当有文件添加进来的时候

uploader.on( 'fileQueued', function( file ) {

    var $li = $(

            '<div id="' + file.id + '" class="file-item thumbnail">' +

                '<img>' +

                '<div class="info">' + file.name + '</div>' +

            '</div>'

            ),

        $img = $li.find('img')

    // $list为容器jQuery实例

    $list.append( $li )

    // 创建缩略图

    // 如果为非图片文件,可以不用调用此方法。

    // thumbnailWidth x thumbnailHeight 为 100 x 100

    uploader.makeThumb( file, function( error, src ) {

        if ( error ) {

            $img.replaceWith('<span>不能预览</span>')

            return

        }

        $img.attr( 'src', src )

    }, thumbnailWidth, thumbnailHeight )

})

然后剩下的就是上传状态提示了,当文件上传过程中, 上传成功,上传失败,上传完成都分别对应uploadProgress, uploadSuccess, uploadError, uploadComplete事件。

// 文件上传过程中创建进度条实时显示。

uploader.on( 'uploadProgress', function( file, percentage ) {

    var $li = $( '#'+file.id ),

        $percent = $li.find('.progress span')

    // 避免重复创建

    if ( !$percent.length ) {

        $percent = $('<p class="progress"><span></span></p>')

                .appendTo( $li )

                .find('span')

    }

    $percent.css( 'width', percentage * 100 + '%' )

})

// 文件上传成功,给item添加成功class, 用样式标记上传成功。

uploader.on( 'uploadSuccess', function( file ) {

    $( '#'+file.id ).addClass('upload-state-done')

})

// 文件上传失败,显示上传出错。

uploader.on( 'uploadError', function( file ) {

    var $li = $( '#'+file.id ),

        $error = $li.find('div.error')

    // 避免重复创建

    if ( !$error.length ) {

        $error = $('<div class="error"></div>').appendTo( $li )

    }

    $error.text('上传失败')

})

// 完成上传完了,成功或者失败,先删除进度条。

uploader.on( 'uploadComplete', function( file ) {

    $( '#'+file.id ).find('.progress').remove()

})

更多细节,请查看js源码。