java中的上传下载----ajaxFileUpload+struts2
文件上传在项目中应该是非常常见的,而且很多时候,上传文件都只是一个小页面中的一个功能,要求在实现文件上传的前提下不刷新页面。而一般情况下将客户端的文件包装成网络地址传递到服务器端然后通过流来进行文件传输的任务都是使用浏览器来帮我们完成的,一般情况下,我们的form表单提交,我们自己可以手动拿到表单的值,然后封装起来,发送ajax请求,为了安全着想,js是不允许访问客户端的文件系统的,所以而文件传输需要浏览器来完成,ajax上传其实是在页面中一小块区域加一个iframe对象然后引用到另一个页面,提交引用的那个页面。
1、ajaxFileUpload文件下载地址 http://www.phpletter.com/Demo/AjaxFileUpload-Demo/
2、
jsp页面
(<input type="file"/>默认的样式很丑,调整样式有点小麻烦)
我没有加表单,ajax提交表单应该没什么问题,方法很多网上百度

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/ajaxfileupload.js"></script>
<script type="text/javascript">
function ajaxFileUpload()
{ $("#loading")
.ajaxStart(function(){
$(this).show();
})//开始上传文件时显示一个图片
.ajaxComplete(function(){
$(this).hide();
});//文件上传完成将图片隐藏起来 $.ajaxFileUpload
(
{
url:'fileAction.action',//用于文件上传的服务器端请求地址
secureuri:false,//一般设置为false
fileElementId:'file',//文件上传空间的id属性 <input type="file" id="file" name="file" />
dataType: 'json',//返回值类型 一般设置为json
success: function (data, status) //服务器成功响应处理函数
{
//从服务器返回的json中取出message中的数据,其中message为在struts2中定义的成员变量
alert(data.message);
},
error: function (data, status, e)//服务器响应失败处理函数
{
alert(e);
}
}
)
} function f_DL(){
location.href="fileAction!download.action?filePath="+"D:\\apache-tomcat-7.0.41\\webapps\\ajaxFileUploadDemo\\upload\\1P5521N4-3.jpg";
}
</script>
</head>
<body>
<img src="loading.gif" id="loading" style="display: none;">
<input type="file" id="file" name="file" />
<br />
<input type="button" value="上传" onclick="ajaxFileUpload();"> <input type="button" value="下载" onclick="f_DL()"/>
</body>
</html>

3、action
package com.demo.action; import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; @SuppressWarnings("serial")
public class FileAction extends ActionSupport { private File file;
private String fileFileName;
private String fileFileContentType;
private String message = "0"; // 0格式错误 1成功(文件路径) 2失败
private String filePath; public String getFilePath() {
return filePath;
} public void setFilePath(String filePath) {
this.filePath = filePath;
} public String getMessage() {
return message;
} public void setMessage(String message) {
this.message = message;
} public File getFile() {
return file;
} public void setFile(File file) {
this.file = file;
} public String getFileFileName() {
return fileFileName;
} public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
} public String getFileFileContentType() {
return fileFileContentType;
} public void setFileFileContentType(String fileFileContentType) {
this.fileFileContentType = fileFileContentType;
} @SuppressWarnings("deprecation")
@Override
public String execute() throws Exception { String path = ServletActionContext.getRequest().getRealPath("/upload");
File file = new File(path); // 判断文件夹是否存在,如果不存在则创建文件夹
if (!file.exists()) {
file.mkdir();
}
String[] fileSuffix = new String[] { ".exe" };// 禁止文件
try {
File f = this.getFile();
// 判断文件格式
for (int i = 0; i < fileSuffix.length; i++) {
if (fileFileName.endsWith(fileSuffix[i])) {
message = "0";
return ERROR;
}
}
FileInputStream inputStream = new FileInputStream(f);
FileOutputStream outputStream = new FileOutputStream(path + "\\"
+ fileFileName);
byte[] buf = new byte[1024];
int length = 0;
while ((length = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, length);
}
inputStream.close();
outputStream.flush();
message = path + "\\" + this.getFileFileName();
} catch (Exception e) {
e.printStackTrace();
message = "2";
}
return SUCCESS;
} public String download() {
String path = filePath;
HttpServletResponse response = ServletActionContext.getResponse();
try {
// path是指欲下载的文件的路径。
File file = new File(path);
// 取得文件名。
String filename = file.getName();
// 取得文件的后缀名。
String ext = filename.substring(filename.lastIndexOf(".") + 1)
.toUpperCase(); // 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
String filenameString = new String(filename.getBytes("gbk"),
"iso-8859-1");
response.addHeader("Content-Disposition", "attachment;filename="
+ filenameString);
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response
.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return null;
} }

4、struts2配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="struts2" namespace="/" extends="json-default">
<action name="fileAction" class="com.demo.action.FileAction">
<result type="json" name="success">
<param name="contentType">
text/html
</param>
</result>
<result type="json" name="error">
<param name="contentType">
text/html
</param>
</result>
</action>
</package>
</struts>

java中的上传下载----ajaxFileUpload+struts2的更多相关文章
- JAVA 实现FTP上传下载(sun.net.ftp.FtpClient)
package com.why.ftp; import java.io.DataInputStream; import java.io.File; import java.io.FileInputSt ...
- java实现文件上传下载
喜欢的朋友可以关注下,粉丝也缺. 今天发现已经有很久没有给大家分享一篇技术文章了,于是想了一下给大家分享一篇java实现文件上传下载功能的文章,不喜欢的希望大家勿喷. 想必大家都知道文件的上传前端页面 ...
- Java中FTPClient上传中文目录、中文文件名乱码问题解决方法【好用】
转: Java中FTPClient上传中文目录.中文文件名乱码问题解决方法 问题描述: 使用org.apache.commons.net.ftp.FTPClient创建中文目录.上传中文文件名时,目录 ...
- CentOS下安装配置NFS并通过Java进行文件上传下载
1:安装NFS (1)安装 yum install nfs-utils rpcbind (2)启动rpcbind服务 systemctl restart rpcbind.service 查看服务状态 ...
- securecrt中使用上传下载sftp
securecrt中使用上传下载sftp SecureCRT这个工具自带了一个FTP,方便我们上传和下载,而且做的比较人性化,由于其基本命令和linux中基本命令大都相似,熟悉LINUX人能很容易 ...
- java+大文件上传下载
文件上传下载,与传统的方式不同,这里能够上传和下载10G以上的文件.而且支持断点续传. 通常情况下,我们在网站上面下载的时候都是单个文件下载,但是在实际的业务场景中,我们经常会遇到客户需要批量下载的场 ...
- java web 文件上传下载
文件上传下载案例: 首先是此案例工程的目录结构:
- FasfDFS整合Java实现文件上传下载
文章目录 一 : 添加配置文件 二 : 加载配置文件 1. 测试加载配置文件 2. 输出配置文件 三:功能实现 1.初始化连接信 ...
- fastDFS与java整合文件上传下载
准备 下载fastdfs-client-java源码 源码地址 密码:s3sw 修改pom.xml 第一个plugins是必需要的,是maven用来编译的插件,第二个是maven打源码包的,可以不要. ...
随机推荐
- Three.js基础
Three.js基础探寻一 Three.js基础探寻一 1.webGL 一种网络标准,定义了一些较底层的图形接口. 2.Three.js 一个3Djs库,webGL开源框架中比较优秀的一个.除了w ...
- rdlc部署zt
原文:rdlc部署zt 偶然间遇到“ 未能加载文件或程序集microsoft.reportviewer.winforms ……”的一个错误,以前web是遇到过,没想到winform部署也会遇到.找了半 ...
- org.springframework.context.event.AbstractApplicationEventMulticaster
private Collection<ApplicationListener<?>> retrieveApplicationListeners(ResolvableType e ...
- Windows DDB和DIB技术应用(3)--图元外边矩形检测
GDI/GDI+中只有对字体的外边框的测量,而没有提供对点,线,面,曲线的外边框获取函数.下面是本人利用DIB技术编写的探测简单图元,甚至也可以探测自己定义的复杂图元的外边矩形框的函数.本人已经测试, ...
- logstash indexer和shipper的配置
[elk@zjtest7-frontend config]$ cat logstash_agent.conf input { file { type => "zj_nginx_acce ...
- linux下主要是VirtualBox及GuestAdditions的安装
Linux版本的VirtualBox下载:http://www.virtualbox.org/wiki/Linux_Downloads.请下载对应的版本. RedHat.RHEL:rpm -i vh ...
- MySQL- InnoDB锁机制
InnoDB与MyISAM的最大不同有两点:一是支持事务(TRANSACTION):二是采用了行级锁.行级锁与表级锁本来就有许多不同之处,另外,事务的引入也带来了一些新问题.下面我们先介绍一点背景知识 ...
- sql server 存储过程分隔split
CREATE FUNCTION [dbo].[F_split] ( ), ) ) , ), f )) --实现split功能 的函数 AS BEGIN DECLARE @i INT SET @Sour ...
- Java 基本日期类使用(一)
一.java.util.Date Date表示特定的瞬间,精确到毫秒,其子类有Date.Time.Timestap.默认情况下输出的Date对象为:Mon Oct 13 17:48:47 CST 20 ...
- Oracle EBS Concurrent Request:Gather Schema Statistics[Z]
Oracle EBS 的Concurrent Request"Gather Schema Statistics"是一个和性能相关的Concurrent Program,它会对表,列 ...