Struts1上传下载文章分类:Java编程 FileAction
package com.action;
import org.apache.struts.action.*;
import javax.servlet.http.*;
import com.actionForm.FileActionForm;
import org.apache.struts.actions.DispatchAction;
import java.util.Date;
import java.text.*;
import org.apache.struts.upload.FormFile;
import java.io.*;
import java.net.URLEncoder;
import com.dao.*;
public class FileAction extends DispatchAction {
private JDBConnection connection =new JDBConnection();
//以下方法实现文件的上传
public ActionForward upLoadFile(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws
Exception {
ActionForward forward=null;
Date date = new Date();
FileActionForm fileActionForm = (FileActionForm) form;
//FormFile用于指定存取文件的类型
FormFile file = fileActionForm.getFile(); //获取当前的文件
// 获得系统的绝对路径 String dir = servlet.getServletContext().getRealPath("/image");
//我上传的文件没有放在服务器上。而是存在D:D:\\loadfile\\temp\\
String dir="D:\\loadfile\\temp\\";
int i = 0;
String type = file.getFileName();
while(i!=-1){
//找到上传文件的类型的位置,这个地方的是'.'
i = type.indexOf(".");
/**//* System.out.println(i);*/
/**//*截取上传文件的后缀名,此时得到了文件的类型*/
type = type.substring(i+1);
}
// 限制上传类型为jpg,txt,rar;
if (!type.equals("jpg") && !type.equals("txt")&& !type.equals("bmp"))
{//当上传的类型不为上述类型时,跳转到错误页面。
forward=mapping.findForward("error");
}
else
{
// 将上传时间加入文件名(这个地方的是毫秒数)
String times = String.valueOf(date.getTime());
//组合成 time.type
String fname = times + "." + type;
//InInputStream是用以从特定的资源读取字节的方法。
InputStream streamIn = file.getInputStream(); //创建读取用户上传文件的对象
//得到是字节数,即byte,我们可以直接用file.getFileSize(),也可以在创建读取对象时用streamIn.available();
// int ok=streamIn.available();
int ok=file.getFileSize();
String strFee = null;
//这个地方是处理上传的为M单位计算时,下一个是以kb,在下一个是byte;
if(ok>=1024*1024)
{
float ok1=(((float)ok)/1024f/1024f);
DecimalFormat myformat1 = new DecimalFormat("0.00");
strFee = myformat1.format(ok1)+"M";
System.out.println(strFee+"M");
}
else if(ok>1024 && ok<=1024*1024)
{
double ok2=((double)ok)/1024;
DecimalFormat myformat2=new DecimalFormat("0.00");
strFee = myformat2.format(ok2)+"kb";
System.out.println(strFee+"kb");
}
else if(ok<1024)
{
System.out.println("aaaaaaaaa");
strFee=String.valueOf(ok)+"byte";
System.out.println(strFee);
}
System.out.println( streamIn.available()+"文件大小byte");
//这个是io包下的上传文件类
File uploadFile = new File(dir); //指定上传文件的位置
if (!uploadFile.exists() || uploadFile == null) { //判断指定路径dir是否存在,不存在则创建路径
uploadFile.mkdirs();
}
//上传的路径+文件名
String path = uploadFile.getPath() + "\\" + fname;
//OutputStream用于向某个目标写入字节的抽象类,这个地方写入目标是path,通过输出流FileOutputStream去写
OutputStream streamOut = new FileOutputStream(path);
int bytesRead = 0;
byte[] buffer = new byte[8192];
//将数据读入byte数组的一部分,其中读入字节数的最大值是8192,读入的字节将存储到,buffer[0]到buffer[0+8190-1]的部分中
//streamIn.read方法返回的是实际读取字节数目.如果读到末尾则返回-1.如果bytesRead返回为0则表示没有读取任何字节。
while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) {
//写入buffer数组的一部分,从buf[0]开始写入并写入bytesRead个字节,这个write方法将发生阻塞直至字节写入完成。
streamOut.write(buffer, 0, bytesRead);
}
// 关闭输出输入流,销毁File流。
streamOut.close();
streamIn.close();
file.destroy();
String paths=path;
System.out.println(paths);
String fileName = Chinese.toChinese(fileActionForm.getFileName()); //获取文件的名称
//String fileSize = String.valueOf(file.getFileSize());
String fileDate = DateFormat.getDateInstance().format(date);
String sql = "insert into tb_file values('" + fileName + "','" +
strFee + "','" + fileDate + "','" + paths + "')";
connection.executeUpdate(sql);
connection.closeConnection();
forward=mapping.findForward("upLoadFileResult");
}
return forward;
}
//实现文件的下载
public ActionForward downFile(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws
Exception {
String path = request.getParameter("path");
System.out.println(path+"111");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
OutputStream fos = null;
InputStream fis = null;
//如果是从服务器上取就用这个获得系统的绝对路径方法。 String filepath = servlet.getServletContext().getRealPath("/" + path);
String filepath=path;
System.out.println("文件路径"+filepath);
File uploadFile = new File(filepath);
fis = new FileInputStream(uploadFile);
bis = new BufferedInputStream(fis);
fos = response.getOutputStream();
bos = new BufferedOutputStream(fos);
//这个就就是弹出下载对话框的关键代码
response.setHeader("Content-disposition",
"attachment;filename=" +
URLEncoder.encode(path, "utf-8"));
int bytesRead = 0;
//这个地方的同上传的一样。我就不多说了,都是用输入流进行先读,然后用输出流去写,唯一不同的是我用的是缓冲输入输出流
byte[] buffer = new byte[8192];
while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.flush();
fis.close();
bis.close();
fos.close();
bos.close();
return null;
}
}
FileActionForm
package com.actionForm;
import org.apache.struts.action.*;
import org.apache.struts.upload.*;
public class FileActionForm extends ActionForm {
private String fileName;//上传文件的名称
private String fileSize;//上传文件的大小
private String filePath;//上传文件到服务器的路径
private String fileDate;//上传文件的日期
private FormFile file;//上传文件
public String getFileName() {
return fileName;
}
public FormFile getFile() {
return file;
}
public String getFileSize() {
return fileSize;
}
public String getFilePath() {
return filePath;
}
public String getFileDate() {
return fileDate;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public void setFile(FormFile file) {
this.file = file;
}
public void setFileSize(String fileSize) {
this.fileSize = fileSize;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public void setFileDate(String fileDate) {
this.fileDate = fileDate;
}
}
index.jsp
<table width="264" height="81" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td width="115" rowspan="4" align="center"><img src="<%=form.getFilePath()%>" width="100" height="100"></td>
<td width="133" align="center">图片名称:<%=form.getFileName()%></td>
</tr>
<tr align="center">
<td>图片大小:<%=form.getFileSize()%></td>
</tr>
<tr align="center">
<td>上传日期:<%=form.getFileDate()%></td>
</tr>
<tr>
<td align="center"><a href="fileAction.do?method=downFile&path=<%=form.getFilePath()%>" ><img src="priture/bottond.jpg"></a>
</td>
</tr>
</table>
<html:form action="fileAction.do?method=upLoadFile" enctype="multipart/form-data" οnsubmit="return Mycheck()">
<table height="52" border="0" align="center" cellpadding="0" cellspacing="0">
<tr align="center">
<td width="60" height="26">图片名称:</td>
<td width="160"> <html:text property="fileName"/> </td>
<td width="60">图片路径:</td>
<td width="198"> <html:file property="file"/> </td>
</tr>
<tr align="right">
<td height="26" colspan="4"> <html:submit>上传</html:submit> </td>
</tr>
</table>
</html:form>
struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">
<struts-config>
<form-beans>
<form-bean name="fileActionForm" type="com.actionForm.FileActionForm" />
</form-beans>
<action-mappings>
<action name="fileActionForm" parameter="method" path="/fileAction" scope="request" type="com.action.FileAction" validate="true">
<forward name="upLoadFileResult" path="/result.jsp"/>
<forward name="error" path="/fail.jsp"></forward>
</action>
</action-mappings>
<message-resources parameter="ApplicationResources" />
</struts-config>
注意要想实现下载的时候弹出另存为对话框,必须满足两个条件:
1.加载commons-upload.jar包
2.以form表单的形式提交报表
具体实例:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ include file="/pages/common/global.jsp"%>
<html>
<head>
<title>高德软件</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<%@ include file="/pages/common/jquery.jsp"%>
<script src="${contextPath }/js/simpleajax.js"></script>
<script src="${contextPath }/js/datepicker/WdatePicker.js" defer="defer"></script>
<style type="text/css">
<!--
body {
margin-left: 0px;
margin-top: 0px;
margin-right: 0px;
margin-bottom: 0px;
}
.STYLE1 {
font-size: 12px;
}
.STYLE3 {
font-size: 12px;
font-weight: bold;
}
.STYLE4 {
color: #03515d;
font-size: 12px;
}
-->
</style>
<script type="text/javascript">
function gotoPage(currentPage,form) {
alert("page");
goto_Page(currentPage,form,"userDiv");
}
function downfile(thisForm, count) {
//submitForm(thisForm); //这种方式提交不行,retrieveURL也不行,必须以下面这种方式
thisForm.action = "${contextPath }/logAction.do?method=downFile&count=" + count + "&rondom=" + Math.random();
thisForm.submit();
}
</script>
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>
<html:form action="/logAction.do?method=downFile">
<table width="100%" border="0" cellpadding="0" cellspacing="1"
bgcolor="b5d6e6" >
<tr>
<td width="3%" height="22" colspan="7" background="${contextPath }/images/tab/bg_15.jpg"
bgcolor="#FFFFFF">
<table width="100%" border="0" cellspacing="0"
cellpadding="0">
<tr>
<td width="3%">
<div align="center">
<img src="${contextPath }/images/tab/vmware16.png" width="16" height="16" />
</div>
</td>
<td width="97%" class="STYLE1">
<span class="STYLE3">日志下载
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="5%" height="22" background="${contextPath }/images/tab/bg.gif"
bgcolor="#FFFFFF">
<div align="center">
<span class="STYLE1">序号</span>
</div>
</td>
<td width="20%" height="22" background="${contextPath }/images/tab/bg.gif"
bgcolor="#FFFFFF">
<div align="center">
<span class="STYLE1">日志日期</span>
</div>
</td>
<td width="40%" height="22" background="${contextPath }/images/tab/bg.gif"
bgcolor="#FFFFFF">
<div align="center">
<span class="STYLE1">日志名称</span>
</div>
</td>
<td width="20%" height="22" background="${contextPath }/images/tab/bg.gif"
bgcolor="#FFFFFF">
<div align="center">
<span class="STYLE1">文件体积</span>
</div>
</td>
<td width="15%" height="22" background="${contextPath }/images/tab/bg.gif"
bgcolor="#FFFFFF">
<div align="center">
<span class="STYLE1">日志下载</span>
</div>
</td>
</tr>
<c:forEach var="varLogList" items="${logList}" varStatus="status">
<tr οnmοuseοver="changeto()" οnmοuseοut="changeback()">
<td height="20" bgcolor="#FFFFFF">
<div align="center">
${status.count }
</div>
</td>
<td height="20" bgcolor="#FFFFFF">
<div align="center">
${varLogList.date }
</div>
</td>
<td height="20" bgcolor="#FFFFFF" >
<div align="center">
${varLogList.fileName }
</div>
</td>
<td height="20" bgcolor="#FFFFFF">
<div align="center">
${varLogList.size }
</div>
</td>
<td height="20" bgcolor="#FFFFFF">
<div align="center">
<input type="hidden" id="filePath" name="filePath${status.count }" value="${varLogList.filePath }" />
<input type="hidden" id="filePath" name="fileName${status.count }" value="${varLogList.fileName }" />
<input type="button" class="button4C" value="下 载" οnclick="javascript:downfile(this.form, '${status.count }');"/>
</div>
</td>
</tr>
</c:forEach>
<c:if test="${empty logList }">
<tr>
<td align="center" colspan="6" height="20" bgcolor="#FFFFFF">
没有找到相关数据。
</td>
</tr>
</c:if>
</table>
</html:form>
</td>
</tr>
</table>
</td>
</tr>
</table>
<script>
try{
//$("#infoDiv").load("${contextPath }/appGrpAction.do?method=basepage");
changeButLi(1);
monitorTree();
tree.closeAllItems();
tree.openItem("-1");
}catch(e){}
$('#container-1').tabs(1,{remote:true,spinner:'',onHide:function(clicked,show,hide){
$(hide).empty();
}});
//refreshTree();
</script>
</body>
</html>
<script><!--
function deleteUser(url){
if(confirm("确实要删除该用户么?")){
retrieveURL(url,null,null,afterDelteUser);
}
}
function afterDelteUser(content){
if(content!=null&&content!=""){
var arr = content.split(",");
alert(arr[1]);
if(arr[0]=="true"){
//retrieveURL("${contextPath}/userAction.do?method=userList","actionDiv");
var url = "${contextPath}/pages/user/userbasepage.jsp";
window.parent.frames["rightFrame"].location = url;
}
}
}
function toModifyUser(url,div){
$("#container").hide();
retrieveURL(url,div,null,after2ModifyUser);
}
function after2ModifyUser(content){
if(content!=null&&content!=""){
var arr = content.split(",");
if(arr[0]=="false"){
$("#chance_search_div").show();
alert(arr[1]);
retrieveURL("${contextPath}/userAction.do?method=userList","actionDiv");
}
}
}
function addUser(url) {
window.parent.frames["rightFrame"].location = url;
}
function gotoPage(currentPage,form) {
goto_Page(currentPage,form,"actionDiv");
}
--></script>
对应的Action方法:
/**
* 实现文件的下载
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward downFile(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
User user = (User) getUser();
if (user == null) {
throw new NotLoginException();
}
String count = request.getParameter("count");
String filePath = request.getParameter("filePath" + count);
String fileName = request.getParameter("fileName" + count);
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
OutputStream fos = null;
InputStream fis = null;
File uploadFile = new File(filePath);
fis = new FileInputStream(uploadFile);
bis = new BufferedInputStream(fis);
fos = response.getOutputStream();
bos = new BufferedOutputStream(fos);
// 这个就就是弹出下载对话框的关键代码
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
int bytesRead = 0;
// 这个地方的同上传的一样。我就不多说了,都是用输入流进行先读,然后用输出流去写,唯一不同的是我用的是缓冲输入输出流
byte[] buffer = new byte[8192];
while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.flush();
fis.close();
bis.close();
fos.close();
bos.close();
return null;
}