六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 26|回复: 0

JQuery.from.js Ajax上传附件

[复制链接]

升级  30%

3

主题

3

主题

3

主题

童生

Rank: 1

积分
15
 楼主| 发表于 2013-2-7 14:55:27 | 显示全部楼层 |阅读模式
使用JQuery.form插件实现无跳转上传。

以下附上简单实现。

准备:commons-fileupload.jar
     commons-io-1.1.jar
     jquery-1.3.1.js
     jquery.form.js

    表单提交脚本:

$(document).ready(function() {    var options = {         target:        '#output2',        beforeSubmit:  showRequest,        success:       showResponse    };    $('#form1').submit(function() {        $(this).ajaxSubmit(options);        return false;//阻止表单提交    });    function showRequest(formData, jqForm, options) {        var queryString = $.param(formData);         alert('queryString==' + queryString);         return true;     }    function showResponse(responseText, statusText) {        alert('status: ' + statusText + '\n\nresponseText:'+responseText);    }});
    html表单:

<form action="MyJsp.jsp" method="post" name="form1" id="form1" enctype="multipart/form-data">    <input type="file" id="file1" name="file1"/><br/>    <input type="text" id="username" name="username" value=""/>    <input type="submit" name="submitButton" value="update">    <div id="output2"></div></form>
    java处理代码:

DiskFileItemFactory factory = new DiskFileItemFactory();String filePath = application.getRealPath("/upload");factory.setRepository(new File(filePath));factory.setSizeThreshold(1024*1024);//创建新的文件上传处理类ServletFileUpload upload = new ServletFileUpload(factory);try {    List list = upload.parseRequest(request);   //处理请求    for(FileItem item : list){        if(item.isFormField()){//表单元素           //String name=item.getFieldName();       //System.out.println("value==>"+item.getString());        }        else {            String name=item.getFieldName();            String value=item.getName();            int start=value.lastIndexOf("\\");            String fileName=value.substring(start+1);            System.out.println("fileName=>"+fileName);            item.write(new File(filePath,fileName));        }    }    response.setContentType("text/html");    response.setCharacterEncoding("GBK");    response.setHeader("cache-control","no-cache");    PrintWriter out = response.getWriter();    out.print("OK");    out.flush();    out.close();} catch (FileUploadException e) {    e.printStackTrace();}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表