标签:
简单的文件上传满足不了需求,我需要做一个异步上传的功能,先写个简单的例子。
Struts2 + Jquery
准备工作:struts2所需jar包,struts2的Json支持,jquery.js ajaxfileupload.js
1:pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zhao</groupId> <artifactId>Struts2</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>Struts2 Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-json-plugin</artifactId> <version>2.3.24</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> </dependency> <!-- Struts2 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.3.24</version> </dependency> </dependencies> <build> <finalName>Struts2</finalName> </build> </project>
在下载好jquery.js和ajaxfileupload.js时需要注意一个问题,ajaxfileupload.js的版本过低,在运行的时候会出错,所以需要在ajaxfileupload.js中补充代码。
我把我用的ajaxfileupload.js补充后的代码放在最后面,用的时候可以直接全部粘贴。
2:ajaxUp.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="jquery-1.12.3.js"></script> <script type="text/javascript" src="ajaxfileupload.js"></script> </head> <body> <script> function ajaxFileUpload(){ $.ajaxFileUpload ( { url:‘fileup.action‘,//用于文件上传的服务器端请求地址 secureuri:false,//一般设置为false fileElementId:‘upload‘,//文件上传空间的id属性 <input type="file" id="file" name="file" /> dataType: ‘json‘, success: function (data) { console.log("success"); }, error: function (data) { console.log("error"); } } ) return false; }; </script> <input type="file" name="upload" id="upload"></input> <button onclick="return ajaxFileUpload();">Submit</button> </body> </html>
需要注意一个问题:在script中的
fileElementId:‘upload‘写的是id 一定要给input type=file加上id,当然name也需要加。
3:Action,
和刚才写的直接上传是一样的。区别在struts.xml中
package com.zhao.action; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import com.opensymphony.xwork2.ActionSupport; /** * * @author: zhao * @time: 2016年5月14日 * * @description:struts2异步上传文件 */ public class FileAction extends ActionSupport{ private static final long serialVersionUID = 1L; private File upload;// 上传文件 private String uploadFileName;// 文件名称 private String uploadContentType;// 文件类型 static final String Path = "E://OA/"; @Override public String execute() throws Exception { InputStream inputStream = new FileInputStream(upload); File target = new File(Path + uploadFileName); OutputStream outputStream = new FileOutputStream(target); System.out.println(upload.getName() + ":" + upload.getPath()); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream); int c; while ((c = bufferedInputStream.read()) != -1) { bufferedOutputStream.write(c); bufferedOutputStream.flush();// 清空缓存 } bufferedInputStream.close(); bufferedOutputStream.close(); return SUCCESS; } public File getUpload() { return upload; } public void setUpload(File upload) { this.upload = upload; } public String getUploadFileName() { return uploadFileName; } public void setUploadFileName(String uploadFileName) { this.uploadFileName = uploadFileName; } public String getUploadContentType() { return uploadContentType; } public void setUploadContentType(String uploadContentType) { this.uploadContentType = uploadContentType; } }
4:struts.xml
注意package继承的是json-default,因为我们用json数据格式。其实写到这就能完美运行了,我还是补充一下js的内容吧.
<package name="json" namespace="/" extends="json-default"> <action name="fileup" class="com.zhao.action.FileAction"> <result type="json"> <param name="contentType"> text/html </param> </result> </action> </package>
5:ajaxfileupload.js
我直接从我项目粘贴过来的,亲测没问题。
// JavaScript Document jQuery.extend({ createUploadIframe: function(id, uri) { //create frame var frameId = ‘jUploadFrame‘ + id; if(window.ActiveXObject) { if(jQuery.browser.version=="9.0") { io = document.createElement(‘iframe‘); io.id = frameId; io.name = frameId; } else if(jQuery.browser.version=="6.0"||jQuery.browser.version=="7.0"||jQuery.browser.version=="8.0") { var io = document.createElement(‘<iframe id="‘ + frameId + ‘" name="‘ + frameId + ‘" />‘); if(typeof uri== ‘boolean‘){ io.src = ‘javascript:false‘; } else if(typeof uri== ‘string‘){ io.src = uri; } } } else { var io = document.createElement(‘iframe‘); io.id = frameId; io.name = frameId; } io.style.position = ‘absolute‘; io.style.top = ‘-1000px‘; io.style.left = ‘-1000px‘; document.body.appendChild(io); return io; }, createUploadForm: function(id, fileElementId) { //create form var formId = ‘jUploadForm‘ + id; var fileId = ‘jUploadFile‘ + id; var form = jQuery(‘<form action="" method="POST" name="‘ + formId + ‘" id="‘ + formId + ‘" enctype="multipart/form-data"></form>‘); var oldElement = jQuery(‘#‘ + fileElementId); var newElement = jQuery(oldElement).clone(); jQuery(oldElement).attr(‘id‘, fileId); jQuery(oldElement).before(newElement); jQuery(oldElement).appendTo(form); //set attributes jQuery(form).css(‘position‘, ‘absolute‘); jQuery(form).css(‘top‘, ‘-1200px‘); jQuery(form).css(‘left‘, ‘-1200px‘); jQuery(form).appendTo(‘body‘); return form; }, handleError: function( s, xhr, status, e ) { // If a local callback was specified, fire it if ( s.error ) { s.error.call( s.context || s, xhr, status, e ); } // Fire the global callback if ( s.global ) { (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] ); } }, ajaxFileUpload: function(s) { // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout s = jQuery.extend({}, jQuery.ajaxSettings, s); var id = s.fileElementId; var form = jQuery.createUploadForm(id, s.fileElementId); var io = jQuery.createUploadIframe(id, s.secureuri); var frameId = ‘jUploadFrame‘ + id; var formId = ‘jUploadForm‘ + id; if( s.global && ! jQuery.active++ ) { // Watch for a new set of requests jQuery.event.trigger( "ajaxStart" ); } var requestDone = false; // Create the request object var xml = {}; if( s.global ) { jQuery.event.trigger("ajaxSend", [xml, s]); } var uploadCallback = function(isTimeout) { // Wait for a response to come back var io = document.getElementById(frameId); try { if(io.contentWindow) { xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null; xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document; }else if(io.contentDocument) { xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null; xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document; } }catch(e) { jQuery.handleError(s, xml, null, e); } if( xml || isTimeout == "timeout") { requestDone = true; var status; try { status = isTimeout != "timeout" ? "success" : "error"; // Make sure that the request was successful or notmodified if( status != "error" ) { // process the data (runs the xml through httpData regardless of callback) var data = jQuery.uploadHttpData( xml, s.dataType ); if( s.success ) { // ifa local callback was specified, fire it and pass it the data s.success( data, status ); }; if( s.global ) { // Fire the global callback jQuery.event.trigger( "ajaxSuccess", [xml, s] ); }; } else { jQuery.handleError(s, xml, status); } } catch(e) { status = "error"; jQuery.handleError(s, xml, status, e); }; if( s.global ) { // The request was completed jQuery.event.trigger( "ajaxComplete", [xml, s] ); }; // Handle the global AJAX counter if(s.global && ! --jQuery.active) { jQuery.event.trigger("ajaxStop"); }; if(s.complete) { s.complete(xml, status); } ; jQuery(io).unbind(); setTimeout(function() { try { jQuery(io).remove(); jQuery(form).remove(); } catch(e) { jQuery.handleError(s, xml, null, e); } }, 100); xml = null; }; } // Timeout checker if( s.timeout > 0 ) { setTimeout(function(){ if( !requestDone ) { // Check to see ifthe request is still happening uploadCallback( "timeout" ); } }, s.timeout); } try { var form = jQuery(‘#‘ + formId); jQuery(form).attr(‘action‘, s.url); jQuery(form).attr(‘method‘, ‘POST‘); jQuery(form).attr(‘target‘, frameId); if(form.encoding) { form.encoding = ‘multipart/form-data‘; } else { form.enctype = ‘multipart/form-data‘; } jQuery(form).submit(); } catch(e) { jQuery.handleError(s, xml, null, e); } if(window.attachEvent){ document.getElementById(frameId).attachEvent(‘onload‘, uploadCallback); } else{ document.getElementById(frameId).addEventListener(‘load‘, uploadCallback, false); } return {abort: function () {}}; }, uploadHttpData: function( r, type ) { var data = !type; data = type == "xml" || data ? r.responseXML : r.responseText; // ifthe type is "script", eval it in global context if( type == "script" ) { jQuery.globalEval( data ); } // Get the JavaScript object, ifJSON is used. if( type == "json" ) { eval( "data = " + data ); } // evaluate scripts within html if( type == "html" ) { jQuery("<div>").html(data).evalScripts(); } return data; } });
标签:
原文地址:http://www.cnblogs.com/zhao307/p/5493082.html