Struts2+ajax+json异步上传图片回显

我们在一个包括很多文本框和上传图片的表单中,为了更好的用户体验需要把点击上传后的图片在提交表单中显示出来,有以下几个方案:

1.  点击上传后获得图片的本地路径,之后显示在网页上,这种方式行不通,因为很多浏览器为了安全性无法获得本地路径。

2.  先把图片异步上传到服务器然后利用回调函数回显图片,由于ajax是不支持带有图片上传的表单提交的,所以我们需要用一些插件,我们的选择有jquery.form.js和ajaxfileupload.js并且请使用jquery-1.4.2-min.js以下版本,或者在高版本中加入

 

    handleError: function( s, xhr, status, e ) {

        // If a local callback was specified, fire it
        if ( s.error ) {
            s.error.call( s.context || s, xhr, status, e );
        }

        // Fire the global callback
        if ( s.global ) {
            (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
        }
    },


 

然而jquery.form.js可以实现上传,但依然无法执行success的回调存在一些BUG

3.  使用ajaxfileupload.js实现

Html

    <img height="100"width="100" src="img/update_pic.png">

    <span style="visibility: hidden">重新上传</span>

       

    <form action="/Struts2Upload/test/upload.action" method="post"enctype="multipart/form-data" id="upfrom">

             <input type="file" id="btn_file" name="btn_file"style="display:none" οnchange="uploadImage();">

             <input type="button" name="btn_abc" value="浏览" οnclick="F_Open_dialog()">

    </form>


JavaScript

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

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

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

    <script type="text/javascript">

        function F_Open_dialog(){

            document.getElementById('btn_file').click();

        }

        function uploadImage() {

            $.ajaxFileUpload({

                url: "/Struts2Upload/test/uploadAjax.action",

                secureuri:false,

                fileElementId:"btn_file",

                dataType: "text",

                beforeSend: function(){

                    $('img').attr('src','img/vote_img_loading.png');

                },

                error: function(data, status, e) {

                    alert(e);

                },

                success: function(data, textStatus){

                    var dataAddr =data.substring(5,data.length-6);

                    dataAddr = eval("(" +dataAddr + ")");

                    $('img').attr('src',dataAddr.imPath);

                }

            });

        } 

    </script>


代码写成这样我们又会发现一些问题dataType返回类型如果是json类型的话,

(1). FF,Chrome会报SynxError这是因为ajaxfileupload.js缺少一段处理


    uploadHttpData:function( r, type ) {

        vardata = !type;

        data= type == "xml" || data ? r.responseXML : r.responseText;

        //If the type is "script", eval it in global context

        if( type == "script" )

            jQuery.globalEval(data );

        //Get the JavaScript object, if JSON is used.

        if( type == "json" ){

            以下为新增代码/// 

            data= r.responseText; 

            varstart = data.indexOf(">"); 

            if(start!= -1) { 

                varend = data.indexOf("<", start + 1); 

                if(end!= -1) { 

                    data= data.substring(start + 1, end); 

                } 

             } 

             ///以上为新增代码///

             eval( "data = " + data );

        }

       //evaluate scripts within html

       if( type == "html" )

           jQuery("<div>").html(data).evalScripts();

       return data;

    }

(2). IE无法执行Ajax请求

这是因为我们使用了button去调用file的原因,IE认为只有用户亲自去点击file才执行form的提交,因此我们需要修改一下代码,原理如下:

让file盖在A标签上面,file设置透明,用户看到A的外观,点击的是file


4.  修改后的ajaxfileupload.js实现

Html

    <img height="100"width="100" src="img/update_pic.png">

    <span style="visibility: hidden">重新上传</span>

    <a style="position:relative;display:block;width:100px;height:30px; 
              background:#EEE;border:0pxsolid #999;text-align:center;" href="javascript:void(0);">

    浏览

        <form action="/Struts2Upload/test/upload.action" method="post"enctype="multipart/form-data" id="upfrom">

            <input type="file" id="btn_file" name="btn_file"οnchange="uploadImage();" 
            style="position:absolute;left:0;top:0;width:100px;height:100%;z-index:999;opacity:0;filter:alpha(opacity=0)">

        </form>

    </a>


JavaScript

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

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

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

    <script type="text/javascript">

        functionuploadImage() {

            $.ajaxFileUpload({

                url:"/Struts2Upload/test/uploadAjax.action",

                secureuri:false,

                fileElementId:"btn_file",

                dataType: "json",

                error: function(data, status, e) {

                    alert(e);

                },

                success: function(data, textStatus) {

                    $('img').attr('src',data.imPath);

                }

            });

        }

    </script>


依赖的Jar


实例Struts2Upload.rar

5.  修改后看似完美了,不过此代码在Chrome下还是会有一个BUG,因为我用的onchange事件会反复触发fileupload导致多次提交上传,最终的代码如下:

Html

<div class="upload-w">
    <img class="u-img" src="/style/js/upload/update_pic.png" id="img1">
    <span class="hide">重新上传</span>
    <div class="btn u-btn">
        大图上传
        <div>
        <input class="u-file" type="file" id="btn_file1" name="btn_file1" data-type="big" data-target="img1" /> 
        </div>
</div>
</div>

JavaScript

$(function(){
    $(".u-file[type=file]").live("change",function(){
	var url = '/proclass/uploadAjax.action';
	var type = $(this).attr("data-type");
	var btnName = $(this).attr("id");
	var imgName = $(this).attr("data-target");
	$.ajaxFileUpload({
	    url: url,
	    secureuri:false,
	    fileElementId:btnName,
	    dataType: "json",
	    data: {//加入的文本参数  
                "photoType": type 
            },
            success: function(data, textStatus) {	
                $('#'+imgName).attr('src',data.data.imPath); 		
            },
            error: function(data, status, e) {
                alert("上传的文件不是图片!!");
            }
        });
    });
});

Css

.upload-w { float:left; margin:10px 20px 10px 0; }
.upload-w .u-img { width:100px; height:100px; border:1px solid #e4e4e4; }
.upload-w .u-btn { position:relative; display:block; text-align:center; }
.upload-w .u-file { position:absolute;left:0;top:0;width:100px;height:100%;z-index:999;opacity:0;filter:alpha(opacity=0); }




 

要实现vue+ajax+php的多图片上传回显,可以按照以下步骤进行: 1.在前端使用Vue的上传组件,设置multiple属性为true,允许用户上传多张图片。 2.在上传组件的change事件中获取用户选择的图片文件,使用FormData对象将图片文件封装成表单数据。 3.使用axios或其他网络请求库将表单数据发送到服务器端。 4.在服务器端接收到表单数据后,解析出图片文件并保存到服务器的指定文件夹中。 5.将图片文件的URL返回给前端,用于回显图片。 下面是一个简单的示例代码: 前端代码: ```html <template> <div> <input type="file" ref="fileInput" @change="handleUploadChange" multiple> <button @click="uploadImages">上传图片</button> <div v-if="imageUrls.length > 0"> <div v-for="imageUrl in imageUrls" :key="imageUrl"> <img :src="imageUrl" style="width: 200px; height: 200px;"> </div> </div> </div> </template> <script> import axios from 'axios' export default { data () { return { imageFiles: [], imageUrls: [] } }, methods: { handleUploadChange () { this.imageFiles = Array.from(this.$refs.fileInput.files) }, uploadImages () { const formData = new FormData() this.imageFiles.forEach(file => { formData.append('images[]', file) }) axios.post('/api/upload_images.php', formData) .then(response => { this.imageUrls = response.data.imageUrls }) .catch(error => { console.log(error) }) } } } </script> ``` 后端代码(使用PHP): ```php <?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { $imageUrls = []; $uploadDir = '/path/to/upload/folder/'; foreach ($_FILES['images']['error'] as $key => $error) { if ($error === UPLOAD_ERR_OK) { $tmpName = $_FILES['images']['tmp_name'][$key]; $fileName = basename($_FILES['images']['name'][$key]); $uploadPath = $uploadDir . $fileName; move_uploaded_file($tmpName, $uploadPath); $imageUrls[] = '/upload/' . $fileName; } } header('Content-Type: application/json'); echo json_encode(['imageUrls' => $imageUrls]); } ``` 在上面的示例代码中,使用了PHP的$_FILES变量来获取上传的图片文件。通过遍历$_FILES['images']['error']数组,可以判断每个文件是否上传成功。如果上传成功,将文件移动到指定的上传目录中,并将文件的URL保存到$imageUrls数组中。最后,将$imageUrls数组以JSON格式返回给前端,用于回显图片。 需要注意的是,上传文件时需要确保服务器端的上传目录有写入权限,否则会导致上传失败。同时,需要对上传的文件进行安全性检查,防止上传恶意文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值