java文件上传--基于ajaxFileUpload+struts2
jQuery插件ajaxFileUpload可以实现ajax文件上传,使用非常简单。
下面做一个简单的demo(以上传图片为例),实现图片上传,图片显示,图片下载
注:以下的代码是在项目的基础上进行开发。css样式文件、包路径等未做修改。
1、 ajaxFileUpload文件下载地址http://www.phpletter.com/Demo/AjaxFileUpload-Demo/
2、自行引入jquery.js、ajaxFileUpload.js文件
jsp核心代码:
<script type="text/javascript">
function fileUpload() {
$.ajaxFileUpload( {
url : 'admin/fileAction.do',//用于文件上传的服务器端请求地址
secureuri : false, //一般设置为false
fileElementId : 'file', //文件上传空间的id属性 <input type="file" id="file" name="file" />
dataType : 'json', //返回值类型 一般设置为json
success : function(data, status) {
$("#downImg").show(); //待上传成功后 显示下载按钮
$("#downImg").attr("href","admin/downloadImage.do?filePath="+data.filePath);
$("#showImg").attr("src","admin/redImage.do?path=" + data.filePath);
}
})
}
</script>
<table class="editTable">
<tr>
<td colspan="4">
<img id="showImg" alt="" src="">
<a id="downImg" style="display: none" href="">下载</a>
</td>
</tr>
<tr>
<td class="title">
上传图片:
</td>
<td colspan="3">
<input type="file" id="file" name="file" onchange="fileUpload();">
</td>
</tr>
</table>
3、AjaxFileUploadAction
public class AjaxFileUploadAction extends WebSupport {
private File file; //文件
private String fileFileName; //文件名
private String filePath; //文件路径
private InputStream inputStream;
/**
* 图片上传
*
* @return
*/
public String fileUpload() {
String path = ServletActionContext.getServletContext().getRealPath("/upload");
File file = new File(path); // 判断文件夹是否存在,如果不存在则创建文件夹
if (!file.exists()) {
file.mkdir();
}
try {
if (this.file != null) {
File f = this.getFile();
String fileName = java.util.UUID.randomUUID().toString(); // 采用时间+UUID的方式随即命名
String name = fileName+ fileFileName.substring(fileFileName.lastIndexOf(".")); // 保存在硬盘中的文件名
FileInputStream inputStream = new FileInputStream(f);
FileOutputStream outputStream = new FileOutputStream(path+ "\\" + name);
byte[] buf = new byte[1024];
int length = 0;
while ((length = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, length);
}
inputStream.close();
outputStream.flush();
//文件保存的完整路径 比如:D:\tomcat6\webapps\eserver\\upload\a0be14a1-f99e-4239-b54c-b37c3083134a.png
filePath = path+"\\"+name;
}
} catch (Exception e) {
e.printStackTrace();
}
return SUCCESS;
}
/**
* 用于图片页面显示
*
* @return
*/
public String readImg() {
try {
inputStream = new FileInputStream(new File(getRequest().getParameter("path")));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return SUCCESS;
}
/**
* 图片下载
* @return
*/
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;
}
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 getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
private static final Logger log = Logger
.getLogger(AjaxFileUploadAction.class);
private static final long serialVersionUID = 1L;
}
4、struts配置
<struts>
<package name="struts_Ajax_code" extends="json-default">
<!-- 文件上传 -->
<action name="fileAction" class="com.bk.eserver.web.action.AjaxFileUploadAction" method="fileUpload">
<result type="json" name="success">
<param name="contentType">text/html</param>
</result>
</action>
</package>
<package name="struts_Jsp_code" extends="struts-default">
<!-- 图片读取 -->
<action name="redImage" class="com.bk.eserver.web.action.AjaxFileUploadAction" method="readImg">
<result type="stream">
<param name="contentType">application/octet-stream</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">attachment;filename=${fileName}</param>
<param name="bufferSize">4096</param>
</result>
</action>
<!-- 文件下载 -->
<action name="downloadImage" class="com.bk.eserver.web.action.AjaxFileUploadAction" method="download">
<result type="stream">
<param name="contentType">application/octet-stream</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">attachment;filename=${fileName}</param>
<param name="bufferSize">4096</param>
</result>
</action>
</package>
</struts>
java文件上传--基于ajaxFileUpload+struts2的更多相关文章
- 小兔Java教程 - 三分钟学会Java文件上传
今天群里正好有人问起了Java文件上传的事情,本来这是Java里面的知识点,而我目前最主要的精力还是放在了JS的部分.不过反正也不麻烦,我就专门开一贴来聊聊Java文件上传的基本实现方法吧. 话不多说 ...
- 2013第38周日Java文件上传下载收集思考
2013第38周日Java文件上传&下载收集思考 感觉文件上传及下载操作很常用,之前简单搜集过一些东西,没有及时学习总结,现在基本没啥印象了,今天就再次学习下,记录下自己目前知识背景下对该类问 ...
- java文件上传-原始的Servlet方式
前言: 干了这几个项目,也做过几次文件上传下载,要么是copy项目以前的代码,要么是百度的,虽然做出来了,但学习一下原理弄透彻还是很有必要的.刚出去转了一圈看周围有没有租房的,在北京出去找房子是心里感 ...
- JAVA文件上传 ServletFileUpLoad 实例
1. jsp <%@ page language="java" contentType="text/html" pageEncoding="u ...
- java文件上传工具包
java 文件上传工具包 主要有两个方法:单文件上传和多文件上传 @Slf4j public class UploadFileUtil { //上传单张图片 public String uploadP ...
- 【Java EE 学习 35 下】【struts2】【struts2文件上传】【struts2自定义拦截器】【struts2手动验证】
一.struts2文件上传 1.上传文件的时候要求必须使得表单的enctype属性设置为multipart/form-data,把它的method属性设置为post 2.上传单个文件的时候需要在Act ...
- java中的上传下载----ajaxFileUpload+struts2
文件上传在项目中应该是非常常见的,而且很多时候,上传文件都只是一个小页面中的一个功能,要求在实现文件上传的前提下不刷新页面.而一般情况下将客户端的文件包装成网络地址传递到服务器端然后通过流来进行文件传 ...
- 十九、多文件上传(ajaxFileupload实现多文件上传功能)
来源于https://www.jb51.net/article/128647.htm 打开google 搜索"ajaxFileupload' ‘多文件上传"可以搜到许许多多类似的, ...
- JQuery文件上传插件ajaxFileUpload在Asp.net MVC中的使用
0 ajaxFileUpload简介 ajaxFileUpload插件是一个非常简单的基于Jquery的异步上传文件的插件,使用过程中发现很多与这个同名的,基于原始版本基础之上修改过的插件,文件版本比 ...
随机推荐
- JavaScript语言基础知识1
我们想知道什么JavaScript.首先,我们必须知道JavaScript有什么特点? JavaScript究竟是什么?它是一种基于对象而且具有安全性的脚本语言,对.它是脚本语言.所以它有下面特点: ...
- JAVA异常处理、常用类、反射、集合
异常 异常:在Java中是指被一个方法抛出的对象. 分类:检查异常.运行时异常.错误 运行时异常(uncheckd):RuntimeException和其子类 检查异常(checkd/搜检异常):指E ...
- 怎样下载并编译Android4.0内核源代码goldfish(图文)
关于怎样下载Android4.0源代码,请查看我的博客内还有一篇文章(相同是图文教程): http://blog.csdn.net/flydream0/article/details/7036156 ...
- C语言学习笔记-顺序表
#include "stdafx.h" #include <stdio.h> #include <stdlib.h> #include "coni ...
- Object-C面向对象之实现类
Object-C面向对象之实现类 一般涉及到面向对象都会C#,Java都不可避免的涉及到类,C#中类的后缀名是.cs,Java中是.java,Object-C中一般用两个文件描述一个类,后缀名为.h为 ...
- css中字符换行的一些问题
-------我们在处理文章的内容的过程中由于文章内容混杂有中文.英文.数字等其他字符,而我们常见的英文和数字是无法在包裹元素中自动换行,这往往会导致元素被撑破,如下图所示: css中word-bre ...
- 关于winlogo.exe中了“落雪”病毒的解决方法
Windows Logon Process,Windows NT 用户登陆程序,管理用户登录和退出.该进程的正常路径应是 C:\Windows\System32 且是以 SYSTEM 用户运行,若不是 ...
- 基于科大讯飞语音云windows平台开发
前记: 前段时间公司没事干,突发奇想想做一个语音识别系统,看起来应该非常easy的,但做起来却是各种问题,这个对电气毕业的我,却是挺为难的.谷姐已经离我们而去,感谢度娘,感谢CSDN各位大神,好歹也做 ...
- EA强大的绘图工具---设计数据库表格
关于EA这个优秀的软件是从师哥哪里听来的,自己瞎点了点,感觉也没什么.近期和和智福加上一个师哥合作敲机房收费系统时,想到之前听人说EA非常强大,便随便找了找关于EA使用的帮助手冊.果然惊喜-- 如题, ...
- POJ 3654 & ZOJ 2936 & HDU 2723 Electronic Document Security(模拟)
题目链接: PKU:http://poj.org/problem?id=3654 ZJU:http://acm.zju.edu.cn/onlinejudge/showProblem.do?proble ...