struts2文件下载 与 jsp文件下载的方式

最开始是先了解 struts2的文件下载,书上云:可以通过<a标签直接来连接目录地址来下载,但是不能实现 中文文件下载(乱码)、隐藏文件在项目中的路径、下载权限(action中、servlet中处理)、设置浏览器不认识的文件类型(如浏览器对txt和图片格式默认不会出现下载提示框而是直接在页面显示,因为浏览器认识它)等等。

为了实现上述功能才用struts2的文件下载,简单方便。

===============struts.xml================

<action name="upload" class="com.kh.action.uploadAction">
            <param name="inputPath">/down/放心.txt</param>
            <result name="success" type="stream">--返回stream流,浏览器接受,然后下载
                <param name="contentType">text/txt</param>
                <param name="inputName">targetFile</param>
                <param name="contentDisposition">attachment;filename="123.txt"</param>
                <param name="bufferSize">4096</param>
            </result>
 </action>

===============jsp==============

  <a href="upload!downString.action">下载</a>

===============action===================

package com.kh.action;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.File;
import java.io.InputStream;

import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class uploadAction extends ActionSupport  

 private String inputPath;  --通过struts.xml的param取值
 public void setInputPath(String inputPath){
     this.inputPath=inputPath;
 }
 public String downString(){
  //下载权限控制
  return SUCCESS;
 }
 public InputStream getTargetFile() throws Exception{    --在result中通过<param  name="inputName">targetFile</param>取值
  return ServletActionContext.getServletContext().getResourceAsStream(inputPath);
 }  //得到要下载的文件流

}

=======================================

看完struts2方法后,不理解这个下载功能到底是谁实现的,action中需要文件流么

随后搜索文章:

1。最直接最简单的,方式是把文件地址直接放到html页面的一个链接中。这样做的缺点是把文件在服务器上的路径暴露了,并且还无法对文件下载进行其它的控制(如权限)。这个就不写示例了。
2。在服务器端把文件转换成输出流,写入到response,以response把文件带到浏览器,由浏览器来提示用户是否愿意保存文件到本地。(示例如下)
<%
 response.setContentType(fileminitype);
 response.setHeader("Location",filename);
 response.setHeader("Cache-Control", "max-age=" + cacheTime);
 response.setHeader("Content-Disposition", "attachment; filename=" + filename); //filename应该是编码后的(utf-8)
 response.setContentLength(filelength);
 OutputStream outputStream = response.getOutputStream();
 InputStream inputStream = new FileInputStream(filepath);
 byte[] buffer = new byte[1024];
 int i = -1;
 while ((i = inputStream.read(buffer)) != -1) {
  outputStream.write(buffer, 0, i);
  }
 outputStream.flush();
 outputStream.close();
 inputStream.close();
 outputStream = null;

%>
3。既然是jsp的话,还有一种方式就是用Applet来实现文件的下载。不过客户首先得信任你的这个Applet小程序,由这个程序来接受由servlet发送来的数据流,并写入到本地。
servlet端示例
    public void service(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        res.setContentType(" text/plain ");
        OutputStream outputStream = null;
        try {
            outputStream = res.getOutputStream();
            popFile(srcFile, outputStream)) ;//把文件路径为srcFile的文件写入到outputStream中。
        } catch (IOException e) {
            e.PRintStackTrace();
        }
    }
JApplet端示例
   URLConnection con;
        try {
            con = url.openConnection();//url是被调用的SERVLET的网址 如http://localhost:8080/sendDateSevlet.do 
            con.setUseCaches(false);
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setRequestProperty("Content-Type",
                "application/octet-stream");
            InputStream in = con.getInputStream();
            ProgressMonitorInputStream pmInputStream = new ProgressMonitorInputStream(
                    pane, "正在从服务器下载文件内容", in);
            ProgressMonitor pMonitor = pmInputStream
                    .getProgressMonitor();
            pMonitor.setMillisToDecideToPopup(3);
            pMonitor.setMillisToPopup(3);
            String localfilepath = localstr + filename ;//localfilepath本地路径,localstr文件文件夹,filename本地文件名
     if(saveFilsaveFilee(localfilepath,pmInputStream)){ //方法saveFilsaveFilee是把输入流pmInputStream写到文件localfilepath中。                   
     openLocalFile(localfilepath);
            }


4。顺便把JApplet上传文件的代码也贴上来.
JApplet端示例

URLConnection con;
        try {
            con = url.openConnection();//url是被调用的SERVLET的网址 如http://localhost:8080/sendDateSevlet.do        
     con.setUseCaches(false);
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setRequestProperty("Content-Type",
                "application/octet-stream");
           
            OutputStream out = con.getOutputStream();
            String localfilepath = localstr + filename; //localfilepath本地路径,localstr文件文件夹,filename本地文件名
            getOutputStream(localfilepath,out);//文件getOutputStream是把文件localfilepath写到输出流out中。
            InputStream in = con.getInputStream();
            return true;
        }catch (IOException e) {
               System.out.println("文件上传出错!");
            e.printStackTrace();
        }

servlet端代码示例
    public void service(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        res.setContentType(" text/plain ");
        InputStream inputStream = null;
        try {
            inputStream = res.getInputStream();
            writefile(srcFile, inputStream);//把输入流inputStream保存到文件路径为srcFile的文件中
        } catch (IOException e) {
            e.printStackTrace();
        }
    } // end service

 总结:在文件的传输中是流的形式存在的,在硬盘上是文件的形式存在的。我们要做的只是通过HttpServletRequest和HttpServletResponse,或者是response和request来发送流和读取流。以及把文件转换成流或把流转换成文件的操作。

-

资料引用:http://www.knowsky.com/344181.html

================总结========

然后明白原来文件下载有两种常用的方式,一种通过<A 的href链接地址去下载文件,第二种在action、servlet中通过i/o对目标下载文件进行流操作,action(struts2)是返回一个流(stream)给浏览器,而servlet则是返回一个response流给浏览器,然后浏览器通过自带的下载功能下载文件到本地。

 

转载于:https://www.cnblogs.com/kaka-bing/archive/2012/07/01/2572006.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值