利用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>

利用struts2进行单个文件,批量文件上传,ajax异步上传以及下载的更多相关文章

  1. spring mvc 文件上传 ajax 异步上传

    异常代码: 1.the request doesn't contain a multipart/form-data or multipart/mixed stream, content type he ...

  2. ajax异步上传文件和表单同步上传文件 的区别

    1. 用表单上传文件(以照片为例)-同步上传 html部分代码:这里请求地址index.php <!DOCTYPE html> <html lang="en"&g ...

  3. 基于Flask开发网站 -- 前端Ajax异步上传文件到后台

    大家好,我是辰哥~ 辰哥最近利用空闲时间在写一个在线可视化平台,过程中也觉得一些技术还是比较有意思的,所以就以模块化的形式分享出来.如:从网页界面(前端)上传文件到服务器(后端). 放一下该模块的界面 ...

  4. html5+php实现文件的断点续传ajax异步上传

    html5+php实现文件的断点续传ajax异步上传 准备知识:断点续传,既然有断,那就应该有文件分割的过程,一段一段的传.以前文件无法分割,但随着HTML5新特性的引入,类似普通字符串.数组的分割, ...

  5. Spring使用ajax异步上传文件

    单文件上传 <!-- 创建文件选择框 --> 文件上传 :<input type="file" id="file" name="fi ...

  6. 基于bootstrap的上传插件fileinput实现ajax异步上传功能(支持多文件上传预览拖拽)

    首先需要导入一些js和css文件 ? 1 2 3 4 5 6 <link href="__PUBLIC__/CSS/bootstrap.css" rel="exte ...

  7. 【文件上传】文件上传的form表单提交方式和ajax异步上传方式对比

    一.html 表单代码 …… <input type="file" class="file_one" name="offenderExcelFi ...

  8. ajax异步上传文件FormDate方式,html支持才可使用

    今天需要做一个头像的预览功能,所以我想到了异步上传文件. 总结几点: 异步上传难点: 文件二进制流如何获取 是否需要设置表单的头,就是content-Type那里.异步,所以无所谓了吧. 其他就差不多 ...

  9. java使用xheditor Ajax异步上传错误

    java使用xheditor Ajax异步上传时候错误如下:the request doesn't contain a multipart/form-data or multipart/mixed s ...

随机推荐

  1. mysql5.6 thread pool

    从percona 的压测来看,确实很牛笔啊.提升很大. http://www.mysqlperformanceblog.com/2014/01/29/percona-server-thread-poo ...

  2. 「雕爷学编程」Arduino动手做(39)——DS18B20温度传感器

    37款传感器与模块的提法,在网络上广泛流传,其实Arduino能够兼容的传感器模块肯定是不止37种的.鉴于本人手头积累了一些传感器和模块,依照实践出真知(一定要动手做)的理念,以学习和交流为目的,这里 ...

  3. React-Redux填坑

    这篇东西以后慢慢补充. Q:今天遇到一个问题是 TypeError:dispatch is not a function A:一直报这个type error,调试了好一阵,最后在tof上看到网友说co ...

  4. django中ckeditor富文本编辑器使用

    1.安装模块 (pillow是python的一个图像处理库) pip install django-ckeditor pip install pillow 2.编辑seetings.py配置文件 IN ...

  5. 6.2 Go 匿名字段

    6.2 Go 匿名字段 Golang匿名字段:可以像访问字段成员那样,访问匿名字段方法,go编译器自动查找. package main import "fmt" type Stud ...

  6. php连接数据库 需要下载adodb

    <?include('adodb/ADOdb.inc.php'); # 加载ADODB$conn = &ADONewConnection('odbc_mssql'); # 建立一个连结$ ...

  7. Closures Basic

    Closures Closures are one of the most powerful features of JavaScript. JavaScript allows for the nes ...

  8. Python一键获取日漫Top100榜单电影信息

    最近看到一个 UP 主做的视频,使用可视化动态图,把目前播放量最多的 UP 主一一列出来,结果第一名是哔哩哔哩番剧,第一名的播放量是第二名近 10 倍. B站的番剧数量,也是相对其他平台比较多的,而且 ...

  9. 5.CSS的引入方式

    CSS的三种样式表 按照CSS样式书写的位置(或者引入的方式),CSS的样式表可以分为三大类: 1.行内样式表(行内式) <div style="color:red: font-siz ...

  10. [json-server] RESTful API 中,取主数据时,同时获取多个关联子表的数据

    项目背景: back-end:ASP.NET Core WebAPI front-end:Vue(+vue-router +vuex +axios)(webpack)(json-server + mo ...