Jquery插件之ajaxfileupload文件上传

来源:互联网 发布:在手机上怎么注册淘宝 编辑:程序博客网 时间:2024/06/14 16:54

ajaxFileUpload是一个异步上传文件的jQuery插件。

语法:$.ajaxFileUpload({options})options参数说明:1、url              上传处理程序服务器地址  2、fileElementId         需要上传的文件域的ID,即<input type="file">的ID3、secureuri          是否启用安全提交,默认为false4、dataType          服务器返回的数据类型,可以为xml,script,json,html。如果不填写,jQuery会自动判断5、success          提交成功后自动执行的处理函数,参数data就是服务器返回的数据6、error            提交失败自动执行的处理函数7、data             自定义参数,当有数据是与上传的图片相关的时候,这个东西就要用到了8、type             当要提交自定义参数时,这个参数要设置成post

以下测试ajaxFileUpload图片上传示例:

一、准备工作: 
① jquery-1.9.1.min.js(这里测试用的是jquery1.9,也可用其它版本 )② ajaxfileupload.js (可在百度搜索下载)③ 引入第三方的一个jar包:commons-fileupload-1.2.2.jar

二、前台页面: 
 
<!DOCTYPE html><html><head>    <meta charset="UTF-8">    <title>图片上传</title>    <script language="javascript" src="js/jquery-1.9.1.min.js" ></script>      <script language="javascript" src="js/ajaxfileupload.js" > </script>    <script type="text/javascript">        $(document).ready(function(){            $('#btnUpload').click(function(){                if($('#fileUpload').val().length > 0) {                    $.ajaxFileUpload({                        url:'/fileupload/upload',                    //服务器端请求地址                        fileElementId:'fileUpload',                 //需要上传的文件域的ID                        secureuri: false,                             //是否启用安全提交,默认为false                        dataType:'json',                            //服务器返回的数据类型                        success:function(data,status){      //服务器成功响应处理函数                            $('#fileShow').append(data.srcHtml);                            $('#msg').html(data.msg);                            //清空上传控件值                            var obj = document.getElementById('fileUpload') ;                            obj.outerHTML = obj.outerHTML;                         },                        error:function(data,status,e){      //服务器响应失败处理函数                            alert(e);                        }                    })                }else{                    alert('请选择图片');                }            })            $('#fileUpload').empty();        })    </script></head><body>    <div>          <input type="file" id="fileUpload" multiple name="fileUpload"/>          <input type="button" id="btnUpload" value="上传图片"/>          <span id="msg" style="color:red"></span>     </div><br>    <div id="fileShow"></div></body></html>
 
三、后台处理: 
public class FileUploadServlet extends HttpServlet {    public void service(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        String filePath = "";   //服务器存放文件路径        String fileName = "";   //文件名        String msg = "";    //错误提示                //获取服务器路径        String basePath = request.getSession().getServletContext().getRealPath("/") + "/upload/";        //判断文件夹是否存在,不存在则创建        File file = new File(basePath);        if(!file.exists()){            file.mkdir();        }        //创建文件上传对象        ServletFileUpload fileUpload = new ServletFileUpload();        fileUpload.setHeaderEncoding("UTF-8");        //判断是否上传了文件        if (fileUpload.isMultipartContent(request)) {            try {                //获取文件上传列表                FileItemIterator fileItems = fileUpload.getItemIterator(request);                //迭代数据                while (fileItems.hasNext()) {                    FileItemStream fis = fileItems.next();                    //判断是否为表单字段                    if (!fis.isFormField() && fis.getName().length() > 0) {                        //获取文件名                        fileName = fis.getName();                         System.out.println("上传的文件名:" + fileName);                        //定义上传文件类型                        Pattern pat = Pattern.compile("[.]jpg|png|jpeg|gif$");                        //判断是否符合定义的类型                        Matcher matcher = pat.matcher(fileName);                          if(!matcher.find()) {                              msg = "请上传图片类型文件";                              break;                         }                        //新文件名                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");                        String newFileName = sdf.format(new Date()) + UUID.randomUUID().toString().replace("-", "") +                                              fileName.substring(fileName.indexOf("."));                        filePath = basePath + newFileName;                                              //获取文件输入流                        BufferedInputStream bis = new BufferedInputStream(fis.openStream());                        //获取文件输出流                        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));                        //设置每次读取的字节数                        byte b[] = new byte[1024];                        //读写文件                        int len = 0;                        while ((len = bis.read(b)) != -1) {                            bos.write(b, 0, len);                        }                        bis.close();                        bos.close();                    }                }            } catch (Exception e) {                e.printStackTrace();            }            //返回页面数据            response.setContentType("text/html;charset=UTF-8");            PrintWriter out = response.getWriter();            if (filePath != "") {                String srcHtml = "<img src='http://localhost:80/fileupload/" +                                         filePath.substring(filePath.indexOf("/")) +"'/>";                out.print("{srcHtml:'"+srcHtml+"'}");            }else {                out.print("{msg:'"+msg+"'}");            }            out.close();        }    }}
 
四、web.xml文件: 
<servlet>    <servlet-name>FileUploadServlet</servlet-name>    <servlet-class>utils.FileUploadServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>FileUploadServlet</servlet-name>    <url-pattern>/upload</url-pattern>  </servlet-mapping>   
 
五、测试效果:


 
 

阅读全文
0 0
原创粉丝点击