`

struts1文件上传和下载

 
阅读更多
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" 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>

 

分享到:
评论

相关推荐

    struts2文件上传和下载

    在Struts2中,文件上传和下载是常见的功能需求,对于用户交互和数据交换至关重要。以下是对这些知识点的详细阐述: 1. **文件上传**: 在Struts2中,文件上传主要依赖于`Commons FileUpload`库,它是一个Apache提供...

    struts2文件上传下载源代码

    在Struts2中,文件上传和下载是常见的功能需求,特别是在处理用户交互和数据交换时。这篇博客文章提供的"struts2文件上传下载源代码"旨在帮助开发者理解和实现这些功能。 文件上传功能允许用户从他们的设备上传文件...

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

    例如,Struts 1和Struts 2在处理文件上传和下载的方式上有显著区别,Struts 2引入了更多面向Action的API和拦截器机制。 5. **源代码分析** 在提供的压缩包文件`upload`中,可能包含了Action类、Struts配置文件、...

    struts1 文件上传 文件下载

    在Struts1中,文件上传和下载是常见的功能,尤其在处理用户交互和数据交换时非常有用。下面将详细介绍如何使用Struts1实现文件上传和下载,以及涉及到的关键知识点。 **一、文件上传** 1. **表单配置**:在HTML...

    Struts1 fileupload Struts1文件上传 源码下载

    Struts1的fileupload的文件上传

    struts2实现文件上传下载

    Struts2是一个强大的MVC(模型-视图-控制器)框架,广泛应用于Java ...以上就是使用Struts2框架实现文件上传下载的基本步骤和关键知识点。在实际开发中,可以根据项目需求进行调整和优化,确保功能的稳定性和安全性。

    struts1和struts2分别实现文件上传下载功能

    Struts1和Struts2是两个非常著名的Java Web框架,它们都提供了处理文件上传和下载的功能,但实现方式有所不同。本文将深入探讨这两个框架在文件操作方面的具体实现。 首先,让我们了解一下Struts1中的文件上传功能...

    struts实现的文件上传下载功能

    在这个特定的场景中,我们关注的是如何使用Struts来实现文件的上传和下载功能。这个功能对于任何Web应用来说都是非常重要的,因为它允许用户交互地处理数据和资源。 首先,我们需要理解文件上传的基本流程。在...

    struts文件上传和下载

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

    用struts1实现文件的上传和下载

    在这个项目中,我们将探讨如何利用Struts1来实现文件的上传和下载功能。 首先,我们需要理解文件上传的基本流程。在Web应用中,用户通过表单提交包含文件的POST请求到服务器。Struts1框架接收到这个请求后,会使用`...

    struts框架-文件上传下载

    1. Struts1中的文件上传:在Struts1中,文件上传主要依赖于`commons-fileupload`和`commons-io`两个库。首先需要在`struts-config.xml`中配置`action`元素,启用流处理。然后在表单中使用`&lt;html:file&gt;`标签指定上传...

    struts2文件上传与下载

    在Struts2中,文件上传和下载是常见的功能需求,主要用于处理用户在Web表单中提交的文件,如图片、文档等。下面将详细介绍Struts2中文件上传和下载的实现方法。 ### 1. 文件上传 #### 1.1 配置Struts2 首先,我们...

    struts1实现文件上传和下载

    在Struts1中,实现文件上传和下载功能是常见的需求,这对于处理用户提交的文件,如图片、文档等,至关重要。下面将详细解释如何在Struts1中实现这两个操作。 首先,我们关注文件上传。在Struts1中,文件上传主要...

    Struts文件的上传和下载

    在Struts框架中,文件的上传和下载是常见的功能需求,用于实现用户交互,如上传图片、文档等,或者提供资源的下载服务。下面将详细探讨Struts中文件上传和下载的实现机制。 一、文件上传 1. 配置文件:在Struts2中...

    Struts2文件上传与下载

    在Web应用中,文件上传和下载是常见的需求,例如用户上传头像、下载文档等。Struts2通过其Action类和Interceptor拦截器机制,简化了这些操作。 文件上传在Struts2中主要依赖于`org.apache.struts2.interceptor....

    struts2文件上传下载

    在这个特定的项目中,我们关注的是"struts2文件上传下载"的功能,这涉及到用户通过Web界面上传文件到服务器,以及从服务器下载文件到用户的设备。 文件上传是Web应用中的常见需求,例如用户可能需要提交图片、文档...

    struts2中的文件上传和下载示例

    Struts2是一个强大的Java web框架,它为开发者提供了丰富的功能,包括文件上传和下载。在Struts2中处理文件上传和下载是常见的需求,对于构建交互式的Web应用来说至关重要。以下将详细介绍Struts2中如何实现这两个...

    struts2 文件的上传和下载

    在Struts2中,文件的上传和下载是常见的功能需求,特别是在处理用户表单提交、数据交换或者提供资源下载服务时。这篇博客文章将探讨如何在Struts2框架下实现文件的上传和下载操作。 首先,我们需要了解文件上传的...

    struts1实现文件上传

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

    struts1 实现文件上传下载

    在Struts1中实现文件上传和下载是常见的需求,这通常涉及到用户通过Web界面交互地上传文件到服务器,或者从服务器下载文件到本地计算机。 一、文件上传 1. **配置ActionForm**:首先,你需要创建一个继承自Struts...

Global site tag (gtag.js) - Google Analytics