JQuery.from.js Ajax上传附件

使用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();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值