利用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>
利用struts2进行单个文件,批量文件上传,ajax异步上传以及下载的更多相关文章
- spring mvc 文件上传 ajax 异步上传
异常代码: 1.the request doesn't contain a multipart/form-data or multipart/mixed stream, content type he ...
- ajax异步上传文件和表单同步上传文件 的区别
1. 用表单上传文件(以照片为例)-同步上传 html部分代码:这里请求地址index.php <!DOCTYPE html> <html lang="en"&g ...
- 基于Flask开发网站 -- 前端Ajax异步上传文件到后台
大家好,我是辰哥~ 辰哥最近利用空闲时间在写一个在线可视化平台,过程中也觉得一些技术还是比较有意思的,所以就以模块化的形式分享出来.如:从网页界面(前端)上传文件到服务器(后端). 放一下该模块的界面 ...
- html5+php实现文件的断点续传ajax异步上传
html5+php实现文件的断点续传ajax异步上传 准备知识:断点续传,既然有断,那就应该有文件分割的过程,一段一段的传.以前文件无法分割,但随着HTML5新特性的引入,类似普通字符串.数组的分割, ...
- Spring使用ajax异步上传文件
单文件上传 <!-- 创建文件选择框 --> 文件上传 :<input type="file" id="file" name="fi ...
- 基于bootstrap的上传插件fileinput实现ajax异步上传功能(支持多文件上传预览拖拽)
首先需要导入一些js和css文件 ? 1 2 3 4 5 6 <link href="__PUBLIC__/CSS/bootstrap.css" rel="exte ...
- 【文件上传】文件上传的form表单提交方式和ajax异步上传方式对比
一.html 表单代码 …… <input type="file" class="file_one" name="offenderExcelFi ...
- ajax异步上传文件FormDate方式,html支持才可使用
今天需要做一个头像的预览功能,所以我想到了异步上传文件. 总结几点: 异步上传难点: 文件二进制流如何获取 是否需要设置表单的头,就是content-Type那里.异步,所以无所谓了吧. 其他就差不多 ...
- java使用xheditor Ajax异步上传错误
java使用xheditor Ajax异步上传时候错误如下:the request doesn't contain a multipart/form-data or multipart/mixed s ...
随机推荐
- clickhouse基本操作一
常用SQL 创建表 1 2 3 4 5 6 7 CREATE TABLE b6logs( eventDate Date, impid UInt64, uid String, idfa String, ...
- 如何覆盖elementUI样式
question: 在某个组件里面更改element-Ui的样式,而不影响全局. solution: 在需要更改的组件里新增一个style标签[重点:不要加scoped],然后直接获取class设置样 ...
- 用了这么多年的 Java 泛型,你对它到底有多了解?
作为一个 Java 程序员,日常编程早就离不开泛型.泛型自从 JDK1.5 引进之后,真的非常提高生产力.一个简单的泛型 T,寥寥几行代码, 就可以让我们在使用过程中动态替换成任何想要的类型,再也不用 ...
- unity-消息的注册,监听,回调
最近在空闲时间准备做个小游戏,先把一些基本框架搭建好,本次记录的是消息的注册,监听和回调等 其实这些就是基于C#的委托(delegate) 第一步:定义一些委托 namespace Common.Me ...
- 洛谷P2468 粟粟的书架
题目链接:https://www.luogu.org/problemnew/show/P2468 知识点: 可持久化线段树.二分.前缀和 解题思路: 对于 \(R, C \le 200, M \le ...
- 【Redis】Hash常见应用场景 - 电商购物车
电商购物车 以用户id为key 商品id为field 商品数量为value 购物车操作 [key(用户id),field(商品id),value(数量)] 添加商品 -> hset cart: ...
- Java并发编程入门(二)
1.竞态条件 1.1 定义 当某个计算的正确性取决于多个线程的交替执行时序时,就会发生竞态条件.换句话说,正确的结果要取决于运气. 最常见的竞态条件类型:先检查后执行(Check-Then-Act)操 ...
- Linux上,最常用的一批命令解析【10年精选】
原文链接:https://mp.weixin.qq.com/s/QkqHexs_kOgy_5OwbwyFww 建议点击原文链接查看 不同平台linux客户端连接工具分享: windos终端神器:SSH ...
- opencv3学习1:opencv3.4.10与vs2017环境配置
原教程网址:https://jingyan.baidu.com/article/dca1fa6f13bd55f1a44052b9.html 具体教程网上很多,我也相信大家的搜素能力,作为一个初入C++ ...
- 封装 private
封装表现: 1.方法就是一个最基本封装体. 2.类其实也是一个封装体. 从以上两点得出结论,封装的好处: 1.提高了代码的复用性. 2.隐藏了实现细节,还要对外提供可以访问的方式.便于调用者的使用.这 ...