Javaweb中的文件下载实现

Javaweb中的文件下载实现,第1张

需要在响应头部加上一些标示,告诉浏览器这个是文件下载。

如果你用了框架比如struts,需要加如下配置

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

<param name="contentType">application/octet-streamcharset=ISO8859-1</param>

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

<param name="contentDisposition">attachmentfilename="${fileName}"</param>

<param name="bufferSize">2048</param>

</result>

如果没有用框架,就手动在返回对象添加这些contentType

import java.io.IOException

import java.io.PrintWriter

import javax.servlet.ServletException

import javax.servlet.http.HttpServlet

import javax.servlet.http.HttpServletRequest

import javax.servlet.http.HttpServletResponse

import com.jspsmart.upload.*

import net.sf.json.JSONObject

import action.StudentAction

public class UploadServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

this.doPost(request, response)

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

boolean result=true

SmartUpload mySmartUpload=new SmartUpload()

mySmartUpload.initialize(this.getServletConfig(), request,response)

mySmartUpload.setTotalMaxFileSize(50*1024*1024)//大小限制

mySmartUpload.setAllowedFilesList("doc,docx")//后缀名限制

try {

mySmartUpload.upload()

com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0)

myFile.saveAs("/file/"+1+".doc")//保存目录

} catch (SmartUploadException e) {

e.printStackTrace()result=false

}

//*****************************//

response.setContentType("text/htmlcharset=UTF-8")

response.setHeader("Cache-Control","no-cache")

PrintWriter out = response.getWriter()

out.print(result)

out.flush()

out.close()

}

}

//我这是ajax方式的,不想这样,把//**********************//以下部分修改就行了

//需要SmartUpload组件,去网上下个就行了,也有介绍的


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

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

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

发表评论

登录后才能评论

评论列表(0条)

保存