利用html5的FileReader对象实现图片预览,利用FormData对象结合struts2实现无刷新文件上传(多参数)

来源:互联网 发布:单片机tssop28封装尺寸 编辑:程序博客网 时间:2024/05/16 12:49

1、页面内容如下:

<div>

         <div class="selectImg">

                   <form action=""id="postForm" enctype="multipart/form-data">

                            <!-- 文件内容变化就调用getImgUrl方法,获取变化后的文件,然后通过fileRead对象生成临时文件,赋值给invoiceImg -->

                            <input type="file" accept="image/*" onchange="getImgUrl"id="invoiceImg" name="invoiceImg" />

                   </form>

                   <!-预览图片的元素 -->

                   <img id="invoiceImg" alt="" />

         </div>

         <div class="btns">

                   <!-- 点击后通过formData对象异步提交上面的form-->

                   <a href="javascript:;" class="weui_btn  weui_btn_primary"onclick="confirmUploadImg">确认收票</a>

 

         </div>

</div>

 

2、JS内容

//预览图片

functiongetImgUrl() {

         if (this.files.length > 0) {

                   if (window.FileReader) {

                            //关键点===============

                            var reader = newFileReader();

                            reader.readAsDataURL(this.files[0]);

                            reader.onload =function(e) {

//赋值给img元素,用于展示

                                               $("#invoiceImg").attr("src",e.target.result);

                                     }

                                     //===============

                   }

         }

 

}

 

//异步上传图片

functionconfirmUploadImg() {

         var _url ="invoiceAction!updateImg";

         var _data = {

                   "test":JSON.stringify({

                            name: '123'

                   }),

                   "id": 1111

         };

         //将其他参数也加入到form表单中,方便其他参数传递

         //清除非文件上传的文本,否则每次添加会导致form表单元素过多

         $("#postForm").find("input").not("[type=file]").remove();

         for (var i in _data) {

                   var val = _data[i];

                   console.log(val);

                   var inputs =document.createElement("input");

                   $(inputs).attr("name",i).attr("value", val);

 //添加元素到表单

                   $("#postForm").append(inputs);

         }

         var formData = newFormData($("#postForm")[0]);

         $.ajax({

                   url: _url,

                   type: 'POST',

                   data: formData,

                   async: false,

                   cache: false,

                   contentType: false,

                   processData: false,

                   success: function(returndata){

                            alert(returndata);

                   },

                   error: function(returndata) {

                            alert(returndata);

                   }

         });

 

}

 

 

3、struts2的action内容

package com.mtx.ent_sale_user.action;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;


import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;


import com.mtx.ent_sale_user.sv.IEntService;


/**
 * 企业员工发票相关
 * @author ylk
 *
 */
public class InvoiceAction extends Ent_SaleBaseAction {


@Autowired
private IEntService iEntService;


private File invoiceImg;
public void setInvoiceImg(File invoiceImg) {
this.invoiceImg = invoiceImg;
}

private String invoiceImgFileName;


public void setInvoiceImgFileName(String invoiceImgFileName) {
this.invoiceImgFileName = invoiceImgFileName;
}




//
private String test;


public void setTest(String test) {
this.test = test;
}

private String id;


public void setId(String id) {
this.id = id;
}




/**
* 上传票图片
*/
public void  updateImg(){
if(null !=invoiceImg){
try {
String name = invoiceImg.getName();
String fileType = invoiceImgFileName.substring(invoiceImgFileName.lastIndexOf("."));
String imageFileName = name.substring(0,name.lastIndexOf("."))+fileType;

String path = ServletActionContext.getServletContext().getRealPath("/invoice");

FileUtils.copyFile(invoiceImg, new File(path,imageFileName));
//读取文件内容
InputStream is = new FileInputStream(invoiceImg);


           File destFile = new File(path, imageFileName);


           OutputStream os = new FileOutputStream(destFile);


           byte[] buffer = new byte[400];


           int length = 0;


           while ((length = is.read(buffer)) > 0) {
               os.write(buffer, 0, length);
           }


           is.close();


           os.close();


} catch (Exception e) {
// TODO: handle exception
}

}

}



}


备注:该方式因依赖与html5的FileReaderformdata对象,所以对浏览器版本要求较高,不兼容低版本。因时间比较匆忙,只是简单的记录了一下,如有看不懂,可以邮箱530331059@qq.com

0 0
原创粉丝点击