利用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 ...
随机推荐
- zabbix server优化与迁移
zabbix server优化与迁移 1. 概述 zabbix 系统其实分3个大部分,一个是server本身,另一个是php的httpd服务,第三个是非常需要优化的数据库.公司的zabbix监控主机在 ...
- MYSQL mysql.user表中权限对应的解释
命令标识 授权表中对应的列 说明 CREATE Create_priv 创建数据库.表或索引 CREATE TEMPORARY TABLES Create_tmp_table_priv 创建临时数据表 ...
- 新概念英语三 新东方主讲Lesson1
新概念二 Lesson95 词汇 ①get a shock 吓了一跳,得到一个惊喜 例:his wife got a shock get into a such mess 这么不幸搞得一片狼籍弄得这样 ...
- 二、HTML基础标签4个
标题标签<h1> —— <h6> <!DOCTYPE html> <html> <head> <meta charset=" ...
- CDN是啥?
CDN 介绍 CDN ( Content Delivery Network ),也即内容分发网络.通过将网站内容(如图片.JavaScript .CSS.网页等)分发至全网加速节点,配合精准智能调度系 ...
- Xftp远程连接出现“无法显示文件夹”的问题补充
网上有很多朋友出现相同的问题,各位热心网友都给出了自己的解决方案,其中大多数网友给出的解决方案都是:将Xftp更换成“被动连接模式”.但是很不幸的是,本人通过这种方式并没有得到有效的解决,网上的各大方 ...
- 突发!HashiCorp禁止在中国使用企业版VAULT软件
目录 前言 HashiCorp公司介绍 HashiCorp旗下的软件 Provision Secure Connect Run 总结 前言 昨天HashiCorp突然发布一则消息,禁止在中国使用Vau ...
- Unable to start services. See log file /tmp/vmware-root/vmware-6853.log for details.
debian安装vmware错误 https://github.com/AdministratorGithub/vmshell vm15.1.0解决linux安装出现Unable to start s ...
- STM32与匿名上位机通信——使用串口DMA实现
背景:匿名上位机功能强大,这里想要采用匿名上位机输出一些调试信息,以波形的形式显示,方便观察和调试. 平台: 硬件:STM32F405RGT6 通信:2.4G zigbee无线串口收发模块 CC253 ...
- Spring相关面试题-整理
1.什么是Spring MVC?简单介绍一下你对Spring MVC的理解? Spring MVC是一个基于Java的实现了MVC设计模式的请求驱动类型的轻量级Web框架,通过把Model,View, ...