|
|
使用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();} |
|