利用struts2进行单个文件,批量文件上传,ajax异步上传以及下载

利用struts2进行单个文件,批量文件上传,ajax异步上传以及下载

1.页面显示代码

<%@ page language="java" import="java.util.*"  pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE >
<html>
<head>
<script type="text/javascript" src="<%=path%>/jsAndCss/jquery-1.11.0.js" ></script>
<script type="text/javascript" src="<%=path%>/jsAndCss/util.js" ></script>
<script type="text/javascript" src="<%=path%>/jsAndCss/ajaxfileupload.js" ></script>
</head>
<body>
<h1>文件表单上传</h1>
<form method = "post" action = "upload.action" enctype=multipart/form-data>
文件 : <input type ="file" name = "myFile">
<input type = "submit" value = "上传">
</form>
<br><br> <h1>文件表单下载</h1>
<form method = "post" action = "download.action" enctype=multipart/form-data>
<input type = "submit" value = "下载">
</form>
<br><br> <h1>文件ajax上传</h1>
<form>
文件 : <input type ="file" name = "myFileAjax" id = "myFileAjax">
<input type = "button" value = "ajax上传" onclick = "updownMgr.upload();">
</form> <br><br>
<h1>批量文件的上传</h1>
<form method = "post" action = "uploadBatch.action" enctype=multipart/form-data>
<!--文件 1: <input type ="file" name = "myFile"><br><br>
文件 2: <input type ="file" name = "myFile"><br><br>
文件 3: <input type ="file" name = "myFile"><br><br>
文件 4: <input type ="file" name = "myFile">
-->
<!--一次按住ctrl可提交多个文件 -->
<input type="file" name="myFile" multiple="multiple">
<input type = "submit" value = "提交"><br><br>
</form> <script type="text/javascript">
var updownMgr = {
upload:function(){
//$.AjaxFileUpload这里不要写成大写的A
$.ajaxFileUpload({
url:'uploadAjax.action',//用于文件上传的请求地址
fileElementId :'myFileAjax',//文件上传空间的id属性,通过这个id,相当于非异步中的myFile
dataType:'text',
success: function(data,status){
alert(data);
},
error: function(data,status,e){
alert(e+"===上传文件失败");
}
});
}
};
</script>
</body>
</html>

二.代码

1.UploadAction.java代码

package org.scs.studystruts2.sysmanage.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; public class UploadAction {
//跟表单提交的input type = file 的name 保持一致
private File myFile; //文件名称 (myFile+myFileFileName)固定格式
private String myFileFileName; //文件类型 myFile+"ContentType"固定格式
private String myFileContentType; //这是我们在action配置里面的参数allowTypes
private String allowTypes; private String message; public File getMyFile() {
return myFile;
}
public void setMyFile(File myFile) {
this.myFile = myFile;
} public String getMyFileFileName() {
return myFileFileName;
}
public void setMyFileFileName(String myFileFileName) {
this.myFileFileName = myFileFileName;
}
public String getMyFileContentType() {
return myFileContentType;
}
public void setMyFileContentType(String myFileContentType) {
this.myFileContentType = myFileContentType;
}
public String getAllowTypes() {
return allowTypes;
}
public void setAllowTypes(String allowTypes) {
this.allowTypes = allowTypes;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
} //默认执行的方法 gotoLogin.action
public String execute(){
return "success";
} public String upload () throws Exception{
//判断文件类型,如果使我们系统允许的文件类型,就进入上传流程,否则给出错误提示
//在action配置了allowTypes参数来定义我们允许的上传类型
boolean allowedFlag = false;
String[] allowTypeArray = allowTypes.split(",");
for(String fileTypes :allowTypeArray){
if(fileTypes.equals(myFileContentType)){
allowedFlag = true;
}
}
if (allowedFlag) {
String uploadRootPath = "D://yu//lou//chun";
File file = new File(uploadRootPath);
if (!file.exists()) {
file.mkdirs();
}
//第二步:我们是不是将我们的文件放入到inputStream里面去了,然后用outputstream写入到文件中
InputStream is = null;
OutputStream os = null;
try {
is =new BufferedInputStream(new FileInputStream(myFile));
os = new BufferedOutputStream(new FileOutputStream(uploadRootPath+"//"+myFileFileName));
byte[] buffer = new byte[1024];
int len =0;
while((len = is.read(buffer)) !=-1){
os.write(buffer, 0, len);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if (os!=null) {
os.flush();
os.close();
}
if (is!=null) {
is.close();
}
}
this.message = "文件上传成功";
return "success";
}else {
this.message = "文件上传失败";
return "fail";
} }
}

2.UploadBatch.java

和单个文件的差不多,只是把相应的改成数组,然后遍历一下

package org.scs.studystruts2.sysmanage.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; public class UploadBatchAction {
//跟表单提交的input type = file 的name 保持一致
private File[] myFile; //文件名称 (myFile+myFileFileName)固定格式
private String[] myFileFileName; //文件类型 myFile+"ContentType"固定格式
private String[] myFileContentType; private String message; public File[] getMyFile() {
return myFile;
} public void setMyFile(File[] myFile) {
this.myFile = myFile;
} public String[] getMyFileFileName() {
return myFileFileName;
} public void setMyFileFileName(String[] myFileFileName) {
this.myFileFileName = myFileFileName;
} public String[] getMyFileContentType() {
return myFileContentType;
} public void setMyFileContentType(String[] myFileContentType) {
this.myFileContentType = myFileContentType;
} public String getMessage() {
return message;
} public void setMessage(String message) {
this.message = message;
} public String uploadBatch () throws Exception{ for (int i = 0; i < myFile.length; i++) {
//第一步设置文件保存的位置
String uploadRootPath = "D://yu//lou//chun";
File file = new File(uploadRootPath);
if (!file.exists()) {
file.mkdirs();
}
//第二步:我们是不是将我们的文件放入到inputStream里面去了,然后用outputstream写入到文件中
InputStream is = null;
OutputStream os = null;
try {
is =new BufferedInputStream(new FileInputStream(myFile[i]));
os = new BufferedOutputStream(new FileOutputStream(uploadRootPath+"//"+myFileFileName[i]));
byte[] buffer = new byte[1024];
int len =0;
while((len = is.read(buffer)) !=-1){
os.write(buffer, 0, len);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if (os!=null) {
os.flush();
os.close();
}
if (is!=null) {
is.close();
}
} }
this.message = "文件上传成功";
return "success";
} }

3.UploadAjax.java

注意引入前端页面引入jquery-1.11.0.js ,  ajaxfileupload.js

  <head>
<script type="text/javascript" src="<%=path%>/jsAndCss/jquery-1.11.0.js" ></script>
<script type="text/javascript" src="<%=path%>/jsAndCss/util.js" ></script>
<script type="text/javascript" src="<%=path%>/jsAndCss/ajaxfileupload.js" ></script>
</head>
 package org.scs.studystruts2.sysmanage.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 java.io.PrintWriter; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; public class UploadAjaxAction {
//跟表单提交的input type = file 的name 保持一致
private File myFileAjax; //文件名称 (myFile+myFileFileName)固定格式
private String myFileAjaxFileName; //文件类型 myFile+"ContentType"固定格式
private String myFileAjaxContentType; private String message; public File getMyFileAjax() {
return myFileAjax;
} public void setMyFileAjax(File myFileAjax) {
this.myFileAjax = myFileAjax;
} public String getMyFileAjaxFileName() {
return myFileAjaxFileName;
} public void setMyFileAjaxFileName(String myFileAjaxFileName) {
this.myFileAjaxFileName = myFileAjaxFileName;
} public String getMyFileAjaxContentType() {
return myFileAjaxContentType;
} public void setMyFileAjaxContentType(String myFileAjaxContentType) {
this.myFileAjaxContentType = myFileAjaxContentType;
} public String getMessage() {
return message;
} public void setMessage(String message) {
this.message = message;
} public String uploadAjax() throws Exception{
//第一步:首先我们需要确定上传过来的文件我们保存在哪里
String uploadRootPath = "D://yu//lou//chun";
File file = new File(uploadRootPath);
if (!file.exists()) {
file.mkdirs();
}
//第二步:我们是不是将我们的文件放入到inputStream里面去了,然后用outputstream写入到文件中
InputStream is = null;
OutputStream os = null;
try {
is =new BufferedInputStream(new FileInputStream(myFileAjax));
os = new BufferedOutputStream(new FileOutputStream(uploadRootPath+"//"+myFileAjaxFileName));
byte[] buffer = new byte[1024];
int len =0;
while((len = is.read(buffer)) !=-1){
os.write(buffer, 0, len);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if (os!=null) {
os.flush();
os.close();
}
if (is!=null) {
is.close();
}
}
this.message = "文件上传成功";
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print(message);
out.flush();
out.close();
return null; }
}

4.Download.java

 package org.scs.studystruts2.sysmanage.action;

 import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream; public class DownloadAction { public InputStream getDownloadFile() throws FileNotFoundException{
return new FileInputStream("D://yu//lou//chun//detail.jpg");
}
public String download(){
return "success";
}
}

5.struts2.xml

 <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd"> <struts>
<package name="loginPackage" namespace="/" extends="struts-default">
<action name="login" class="org.scs.studystruts2.sysmanage.action.LoginAction">
<result name="success" type="dispatcher">/login_suc.jsp</result>
<result name="fail" type="dispatcher">/login_err.jsp</result>
</action> <action name="gotoUpload" class="org.scs.studystruts2.sysmanage.action.UploadAction">
<result name="success" type="dispatcher">/WEB-INF/pages/upload/upload.jsp</result>
</action> <action name="upload" class="org.scs.studystruts2.sysmanage.action.UploadAction" method="upload">
<result name="success" type="dispatcher">/WEB-INF/pages/upload/upload_suc.jsp</result>
<result name="fail" type="dispatcher">/WEB-INF/pages/upload/upload_err.jsp</result>
<!--传递的allowTypes参数 -->
<param name="allowTypes">image/jpeg,image/bmp,image/png,image/gif</param>
</action> <action name="uploadAjax" class="org.scs.studystruts2.sysmanage.action.UploadAjaxAction" method="uploadAjax"> </action> <action name = "download" class = "org.scs.studystruts2.sysmanage.action.DownloadAction" method = "download">
<result type="stream">
<!--inline -->
<param name="contentDisposition">attachment;filename="321.jpg"</param>
<param name="inputName">downloadFile</param>
</result>
</action> <action name="uploadBatch" class="org.scs.studystruts2.sysmanage.action.UploadBatchAction" method="uploadBatch">
<result name="success" type="dispatcher">/WEB-INF/pages/upload/upload_suc.jsp</result>
<result name="fail" type="dispatcher">/WEB-INF/pages/upload/upload_err.jsp</result>
</action> </package>
<!--如果有类似的报错信息则需要加上这段代码,创建临时文件 -->
<constant name="struts.multipart.saveDir" value="/tmp"/>
</struts>
上一篇:Maven工程pom.xml文件秒变gradle工程的命令


下一篇:java编程(1)——servlet和Ajax异步请求的接口编程(没有调用数据库的数据)