`

struts实现文件上传和下载业务

阅读更多

首先建立一个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(".");
  
   
    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 此位置的form是javabeen的对象,这个javabeen中存取的图片的相关信息

<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" onsubmit="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>

分享到:
评论

相关推荐

    struts实现文件上传和下载源代码

    在这个"struts实现文件上传和下载源代码"项目中,我们将会探讨如何使用Struts框架来实现在Web应用中进行文件的上传和下载功能,同时还会关注对于大文件(超过3MB)的处理策略。 1. **文件上传** 文件上传是Web应用...

    struts2文件上传下载源代码

    这篇博客文章提供的"struts2文件上传下载源代码"旨在帮助开发者理解和实现这些功能。 文件上传功能允许用户从他们的设备上传文件到服务器。在Struts2中,这通常通过表单实现,表单包含一个`&lt;input type="file"&gt;`...

    Struts实现文件上传、下载(导入直接运行)

    在这个特定的场景中,我们讨论的是如何使用Struts来实现在Web应用中进行文件的上传和下载功能,并且修复了在下载过程中取消操作可能导致的错误。 文件上传是Web应用中常见的一种需求,比如用户可能需要上传图片、...

    struts 文件上传 Struts实现文件上传

    Struts 是一个基于MVC(Model-View-Controller)...总结,Struts 实现文件上传涉及到配置、表单设计、Action处理和安全控制等多个环节。理解并熟练掌握这些知识点,能帮助开发者在实际项目中高效地处理文件上传需求。

    struts文件上传和下载

    在Struts2中,文件上传和下载是常见的功能需求,主要用于处理用户通过表单提交的文件,或者允许用户从服务器下载文件。这些功能极大地增强了Web应用的交互性和实用性。 在Struts2中实现文件上传,主要涉及到以下几...

    Struts2实现文件上传

    Struts2是一个强大的MVC框架,广泛应用于Java Web开发中,尤其在处理用户表单提交和文件上传等交互场景中表现出色。在这个“Struts2实现文件上传”的主题中,我们将深入探讨如何利用Struts2框架来实现在Web应用中的...

    用struts 实现文件上传下载

    本文将详细介绍如何使用Struts实现文件的上传和下载。 **1. 文件上传** 文件上传主要涉及到以下几个步骤: 1. **配置Struts配置文件**:在struts-config.xml中,你需要定义一个Action,这个Action将处理文件上传...

    基于struts的文件上传下载源代码

    总的来说,"基于Struts的文件上传下载源代码"是一个很好的实践项目,它涵盖了Struts框架的用法,文件上传和下载的实现,以及一些基础的Web开发概念。通过深入研究和模仿这些代码,你可以更好地掌握Java Web开发的...

    使用Struts2实现文件上传和下载的所有方案

    在本文中,我们将深入探讨使用Struts2实现文件上传和下载的各种方案。 ### 文件上传方案 #### 1. 使用Struts2进行文件普通上传 文件上传的核心是处理`multipart/form-data`类型的表单数据。Struts2通过`Struts2-...

    struts 实现文件上传与下载

    ### Struts实现文件上传与下载的关键知识点 #### 一、Struts框架简介 Apache Struts是一个开源的MVC(Model-View-Controller)框架,用于简化Java Web应用程序的开发过程。Struts提供了一系列的工具和服务来帮助...

    struts1实现文件上传

    综上所述,Struts1中的文件上传功能实现涉及到多个核心组件和技术点的综合运用。开发者需要对Struts1框架有深入的理解,并熟练掌握相关API的使用方法。此外,在实际开发过程中还需要注意安全性问题,比如防止恶意...

    struts实现文件上传功能

    在Struts中实现文件上传功能,是一项常见的需求,尤其在处理用户提交的各种文件,如图片、文档等时。这个功能可以帮助开发者将用户选择的文件从客户端传输到服务器端进行存储或者处理。 一、Struts2文件上传的基本...

    struts2文件上传下载实例

    通过使用Maven管理依赖,编写Action类处理业务逻辑,并在Struts2配置文件中定义动作映射,我们可以构建一个用户友好的、安全的文件上传下载系统。这不仅对提高用户体验有重要作用,也是保障数据安全和应用程序稳定性...

    struts+hibernate实现文件上传、下载,以二进制存于数据库

    总结起来,这个项目通过`uploadify`实现文件上传,利用Struts处理请求,结合Hibernate将文件以二进制形式存入数据库,再通过EasyUI创建用户友好的界面进行文件下载。整个流程涉及了前端交互、后端处理、数据库操作...

    Struts2实现文件上传功能

    下面将详细阐述如何使用Struts2来实现文件上传功能。 1. **Struts2文件上传组件** Struts2框架集成了一个名为`struts2-convention-plugin`的插件,它提供了文件上传的支持。主要依赖于`Commons FileUpload`和`...

    struts2文件上传下载

    Struts2作为一个成熟的MVC框架,提供了简单的API和标记库来处理文件上传下载的业务逻辑。下面是基于给定文件内容的知识点详细说明。 ### Struts2文件上传知识点 1. **Struts2的form标签配置** 在Struts2中进行...

    基于Struts2的文件上传下载功能的完整源代码。

    在基于Struts2的文件上传下载功能中,它提供了处理用户上传文件和提供文件下载的服务。这个完整的源代码是实现这些功能的一个实例,经过测试确保了其正确性和可用性。 首先,我们要理解Struts2中的Action类。Action...

    spring+struts+hibernate实现文件的上传和下载

    【Spring+Struts+Hibernate 实现文件上传和下载】 在 J2EE 开发中,文件的上传和下载是一项基础但重要的功能。SSH(Struts、Spring、Hibernate)框架提供了便捷的方式来处理这一问题,无需依赖像 SmartUpload 或 ...

    struts实现文件上传

    Struts 是一个基于MVC(Model-View-...以上就是使用Struts框架实现文件上传的基本流程和关键知识点。在实际开发中,你可能还需要结合具体的业务需求进行定制,如使用数据库记录文件元数据、优化文件存储策略等。

    struts2上传和下载文件详细源码

    - Action类:包含处理文件上传和下载的业务逻辑,如验证文件大小、类型等,并可能有保存上传文件到服务器的逻辑。 - 表单JSP页面:使用Struts2标签库构建表单,包括文件上传字段和提交按钮。 - struts.xml配置...

Global site tag (gtag.js) - Google Analytics