Struts1框架 用Java代码实现文件下载 不d出下载框 代码:

Struts1框架 用Java代码实现文件下载 不d出下载框 代码:,第1张

下载代码:

这里我使用的是SpringMVC,不过它在这里谈答的唯一用途就是用来获取ServletContext对象,这个对象的用途,下面实例中有说明

下载,需要用到两个jar包:commons-fileupload.jar和commons-io.jar

Java代码

import org.springframework.stereotype.Controller

import org.springframework.web.bind.annotation.RequestMapping

import org.springframework.web.context.ServletContextAware

import javax.servlet.ServletContext

import javax.servlet.ServletOutputStream

import javax.servlet.http.HttpServletResponse

import java.io.*

@Controller

public class FileController implements ServletContextAware{

//Spring这里是通过实现ServletContextAware接口来注入ServletContext对象

private ServletContext servletContext

@RequestMapping("file/download")

public void fileDownload(HttpServletResponse response){

//获取网站部署路径(通过ServletContext对象),用于确定下载文件位置,从而实现下载

String path = servletContext.getRealPath("/")

//1.设置文件ContentType类型,这样设置,会自动判断下载文件类型

response.setContentType("multipart/form-data")

//2.设置文件头:最后一个洞侍伍参数是设置下载文件名(假如我们叫a.pdf)

response.setHeader("Content-Disposition", "attachmentfileName="+"a.pdf")

ServletOutputStream out

//通过文件路径获得File对象(假如此路径中有一个download.pdf文件)

File file = new File(path + "download/" + "download.pdf")

try {

FileInputStream inputStream = new FileInputStream(file)

//3.通过response获取ServletOutputStream对象(out)

out = response.getOutputStream()

int b = 0

byte[] buffer = new byte[512]

while (b != -1){

b = inputStream.read(buffer)

//4.写到纳或输出流(out)中

out.write(buffer,0,b)

}

inputStream.close()

out.close()

out.flush()

} catch (IOException e) {

e.printStackTrace()

}

}

@Override

public void setServletContext(ServletContext servletContext) {

this.servletContext = servletContext

}

}

JAVA代码中

public InputStream getInputStream(){

//这里是逻辑部分,下载哪个文件

FileInputStream fis = new FileInputStream( File )

return fis

}

public String testDownload(){

// 中文文件名最好用 URLEncoder.encode 编知知码一下

// 也可通过配置文件方式

response.setHeader("Content-Disposition", "attachmentfilename=文件名")

return "success"

} <action name="download" class="xxx.xxx.FileDownloadAction" method="testDownload">

    <result name="success" type="stream">

    <param name="contentType">陪宏application/excel</param>

    <param name="inputName">inputStream</param>

    <param name="bufferSize"芦猛册>4096</param>

    </result>

</action>

以上手打,还有更详细的设置,可以百度,这里只是一个简单的例子

分析下,如果你要下载某个文件需要向服务器发送请求,然后会在客户端与服务器之间建立一个HTTP连接,服务器接收到你的请求后,向response中写入你要下载的内容,并且由于安全策略的原因,浏览器客户端每次下载文件都会d出保存对话框。

也就是说,如果你要下载文件夹下的所有文件,你就需要对所有文件都发送谈唯请求,并且挨个选择保存位置。

如果要解决上面的问题,你可以按照下面的方式做。

1、建立一个servlet(structs2下应该是action吧),用来接收用户的请求。

2、根据用户的请求,将要下载的内容使用org.apache.tools.zip包下的类进行打包(JDK下也有相应的ZIP处理的类,不过它对于中文的文件名处理有问题)。

注:构造ZipOutputStream时使用HttpServletResponse.getOutputStream()构造。这样向ZipOutputStream中写入的内容,客户端就能直接获取。

以旁虚上,希望对你的帮助,可以的话,请采纳运侍燃。


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/12269591.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-24
下一篇 2023-05-24

发表评论

登录后才能评论

评论列表(0条)

保存