导航:首页 > 文件教程 > servlet大文件下载

servlet大文件下载

发布时间:2024-07-25 06:53:31

① 怎样使用javaweb实现上传视频和下载功能

文件上传就是将客户端资源,通过网路传递到服务器端。

因为文件数据比较大,必须通过文件上传才可以完成将数据保存到数据库端的操作。

文件上传的本质就是IO流操作。

演示:文件上传应该如何操作?

浏览器端:
1.method=post 只有post才可以携带大数据
2.必须使用<input type='file' name='f'>要有name属性
3.encType="multipart/form-data"
服务器端:
request对象是用于获取请求信息。
它有一个方法 getInputStream(); 可以获取一个字节输入流,通过这个流,可以读取到
所有的请求正文信息.
文件上传原理:
浏览器端注意上述三件事,在服务器端通过流将数据读取到,在对数据进行解析.
将上传文件内容得到,保存在服务器端,就完成了文件上传。

注意:在实际开发中,不需要我们进行数据解析,完成文件上传。因为我们会使用文件上传的工具,它们已经封装好的,提供API,只要调用它们的API就可以完成文件上传操作.我们使用的commons-fileupload,它是apache提供的一套开源免费的文件上传工具。

代码演示文件上传的原理:

在WebRoot下新建upload1.jsp

[html]view plain

② 用Java的三大框架实现文件的上传下载,求代码啊,最好是分为action,service,serv

package cn.itcast.struts2.demo1;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

/**
* 完成文件上传 (不是解析上传内容,因为上传内容 由fileUpload拦截器负责解析)
*
* @author seawind
*
*/
public class UploadAction extends ActionSupport {
// 接收上传内容
// <input type="file" name="upload" />
private File upload; // 这里变量名 和 页面表单元素 name 属性一致
private String uploadContentType;
private String uploadFileName;

public void setUpload(File upload) {
this.upload = upload;
}

public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}

public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}

@Override
public String execute() throws Exception {
if (upload == null) { // 通过xml配置 required校验器 完成校验
// 没有上传文件
return NONE;
}
// 将上传文件 保存到服务器端
// 源文件 upload
// 目标文件
File destFile = new File(ServletActionContext.getServletContext()
.getRealPath("/upload") + "/" + uploadFileName);
// 文件复制 使用commons-io包 提供 工具类
FileUtils.File(upload, destFile);
return NONE;
}
}
多文件上传
package cn.itcast.struts2.demo1;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

/**
* 支持多文件上传
*
* @author seawind
*
*/
public class MultiUploadAction extends ActionSupport {
// 接收多文件上传参数,提供数组接收就可以了
private File[] upload;
private String[] uploadContentType;
private String[] uploadFileName;

public void setUpload(File[] upload) {
this.upload = upload;
}

public void setUploadContentType(String[] uploadContentType) {
this.uploadContentType = uploadContentType;
}

public void setUploadFileName(String[] uploadFileName) {
this.uploadFileName = uploadFileName;
}

@Override
public String execute() throws Exception {
for (int i = 0; i < upload.length; i++) {
// 循环完成上传
File srcFile = upload[i];
String filename = uploadFileName[i];

// 定义目标文件
File destFile = new File(ServletActionContext.getServletContext()
.getRealPath("/upload" + "/" + filename));
FileUtils.File(srcFile, destFile);
}
return NONE;
}
}

③ 我写了个下载程序,用Java写的,但是写完以后发现下载大文件的时候报错,内存溢出,能看看是哪的问题么

不能一次读取完,大文件很容易内存溢出。参考下:

publicstaticvoiddownload(Stringpath,HttpServletResponseresponse)throwsException{
try{
Filefile=newFile(path);
if(file.exists()){
Stringfilename=file.getName();
InputStreamfis=newBufferedInputStream(newFileInputStream(file));
response.reset();
response.setContentType("application/x-download");
response.addHeader("Content-Disposition","attachment;filename="+newString(filename.getBytes(),"iso-8859-1"));
response.addHeader("Content-Length",""+file.length());
OutputStreamtoClient=newBufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
byte[]buffer=newbyte[1024*1024*4];
inti=-1;
while((i=fis.read(buffer))!=-1){
toClient.write(buffer,0,i);

}
fis.close();
toClient.flush();
toClient.close();
try{
response.wait();
}catch(InterruptedExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}else{
PrintWriterout=response.getWriter();
out.print("<script>");
out.print("alert("notfindthefile")");
out.print("</script>");
}
}catch(IOExceptionex){
PrintWriterout=response.getWriter();
out.print("<script>");
out.print("alert("notfindthefile")");
out.print("</script>");
}

}

④ struts2的action中去访问一个文件,下载到本地

要通过param来写
<result type="redirectAction">
<param name="namespace">/p1</param> (这里内要写package的容namespace)
<param name="actionName">a1</param> (这里写action的name)
</result>

⑤ jsp 文件上传和下载

1.jsp页面
<s:form action="fileAction" namespace="/file" method="POST" enctype="multipart/form-data">
<!-- name为后台对应的参数名称 -->
<s:file name="files" label="file1"></s:file>
<s:file name="files" label="file2"></s:file>
<s:file name="files" label="file3"></s:file>
<s:submit value="提交" id="submitBut"></s:submit>
</s:form>
2.Action
//单个文件上传可以用 File files,String filesFileName,String filesContentType
//名称要与jsp中的name相同(三个变量都要生成get,set)
private File[] files;
// 要以File[]变量名开头
private String[] filesFileName;
// 要以File[]变量名开头
private String[] filesContentType;

private ServletContext servletContext;

//Action调用的上传文件方法
public String execute() {
ServletContext servletContext = ServletActionContext.getServletContext();
String dataDir = servletContext.getRealPath("磨脊尘/file/upload");
System.out.println(dataDir);
for (int i = 0; i < files.length; i++) {
File saveFile = new File(dataDir, filesFileName[i]);
files[i].renameTo(saveFile);
}
return "success";
}
3.配置上传文件临时文件夹(在struts.xml中配置)
<constant name="struts.multipart.saveDir" value="c:/temp"/>
文件下载
1.下载的url(到Action)
<a href="${pageContext.request.contextPath}/file/fileAction!down.action">下载</a>
2.struts.xml配置
<package name="file" namespace="野神/file" extends="struts-default">
<action name="fileAction" class="com.struts2.file.FileAction">
<!-- 下载文件配置 -->
<!--type 为 stream 应用 StreamResult 处理-->
<result name="down" type="stream">
<!--
不管实际类型,待下载文件 ContentType 统一指定为 application/octet-stream
默认为 text/plain
-->
<param name="contentType">application/octet-stream</param>
<!--
默认就是 inputStream,它将会指示 StreamResult 通过 inputName 属性值的 getter 方法,
比如这里就是 getInputStream() 来获取下载文件的内容,意味着瞎禅你的 Action 要有这个方法
-->
<param name="inputName">inputStream</param>
<!--
默认为 inline(在线打开),设置为 attachment 将会告诉浏览器下载该文件,filename 指定下载文
件保有存时的文件名,若未指定将会是以浏览的页面名作为文件名,如以 download.action 作为文件名,
这里使用的是动态文件名,${fileName}, 它将通过 Action 的 getFileName() 获得文件名
-->
<param name="contentDisposition">attachment;filename="${fileName}"</param>
<!-- 输出时缓冲区的大小 -->
<param name="bufferSize">4096</param>
</result>
</action>
</package>
3.Action
//Action调用的下载文件方法
public String down() {
return "down";
}

//获得下载文件的内容,可以直接读入一个物理文件或从数据库中获取内容
public InputStream getInputStream() throws Exception {
String dir = servletContext.getRealPath("/file/upload");
File file = new File(dir, "icon.png");
if (file.exists()) {
//下载文件
return new FileInputStream(file);

//和 Servlet 中不一样,这里我们不需对输出的中文转码为 ISO8859-1
//将内容(Struts2 文件下载测试)直接写入文件,下载的文件名必须是文本(txt)类型
//return new ByteArrayInputStream("Struts2 文件下载测试".getBytes());
}
return null;
}

// 对于配置中的 ${fileName}, 获得下载保存时的文件名
public String getFileName() {
String fileName ="图标.png";
try {
// 中文文件名也是需要转码为 ISO8859-1,否则乱码
return new String(fileName.getBytes(), "ISO8859-1");
} catch (UnsupportedEncodingException e) {
return "icon.png";
}
}

⑥ resin鏈嶅姟鍣ㄤ笅鐢╦ava涓嬭浇pdf鏂囦欢锛屼笅杞戒笅鏉ョ殑鏂囦欢姣旀簮鏂囦欢澶т簡涓鍊嶅氾紝涓嶈兘鎵撳紑銆

杩欎釜浼间箮鐪熸湁闂棰橈紝鎶婂惊鐜璇诲彇鍜屽啓鍑烘槸涓嶆槸瑕佹敼鎴愯繖鏍锋洿濂戒竴浜
while ((read = input.read(buffBytes,0,1024)) != -1) {
allLength += read;
os.write(buffBytes, 0, read);
}

⑦ jsp+servlet实现文件上传与下载源码

上传:
需要导入两个包:commons-fileupload-1.2.1.jar,commons-io-1.4.jar
import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
* 上传附件
* @author new
*
*/
public class UploadAnnexServlet extends HttpServlet {

private static String path = "";

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doPost(request, response);
}

/*
* post处理
* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

path = this.getServletContext().getRealPath("/upload");

try {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload up = new ServletFileUpload(factory);
List<FileItem> ls = up.parseRequest(request);

for (FileItem fileItem : ls) {
if (fileItem.isFormField()) {
String FieldName = fileItem.getFieldName();
//getName()返回的是文件名字 普通域没有文件 返回NULL
// String Name = fileItem.getName();
String Content = fileItem.getString("gbk");
request.setAttribute(FieldName, Content);
} else {

String nm = fileItem.getName().substring(
fileItem.getName().lastIndexOf("\\") + 1);
File mkr = new File(path, nm);
if (mkr.createNewFile()) {
fileItem.write(mkr);//非常方便的方法
}
request.setAttribute("result", "上传文件成功!");
}
}
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("result", "上传失败,请查找原因,重新再试!");
}
request.getRequestDispatcher("/pages/admin/annex-manager.jsp").forward(
request, response);
}

}

下载(i/o流)无需导包:
import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* 下载文件
* @author
*
*/
public class DownloadFilesServlet extends HttpServlet {

/**
*
*/
private static final long serialVersionUID = 8594448765428224944L;

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doPost(request, response);
}

/*
* 处理请求
* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String name = request.getParameter("fileName");

System.out.print("dddddddddd:" + name);
// web绝对路径
String path = request.getSession().getServletContext().getRealPath("/");
String savePath = path + "upload";

// 设置为下载application/x-download
response.setContentType("application/x-download");
// 即将下载的文件在服务器上的绝对路径
String filenamedownload = savePath + "/" + name;
// 下载文件时显示的文件保存名称
String filenamedisplay = name;
// 中文编码转换
filenamedisplay = URLEncoder.encode(filenamedisplay, "UTF-8");
response.addHeader("Content-Disposition", "attachment;filename="
+ filenamedisplay);
try {
java.io.OutputStream os = response.getOutputStream();
java.io.FileInputStream fis = new java.io.FileInputStream(
filenamedownload);
byte[] b = new byte[1024];
int i = 0;
while ((i = fis.read(b)) > 0) {
os.write(b, 0, i);
}
fis.close();
os.flush();
os.close();
} catch (Exception e) {

}

}

}

⑧ java web 如何获得文件上传大小

有一种叫jspsmartupload的包用来简化文件上传下载的编写
里面可以获取文件大小

//取得文件
com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0);
//取得文件名
String fileName = myFile.getFileName();
//取得文件大小
int fileSize = myFile.getSize();
这是基于spring架构的上传文件支持多个文件上传,拿到file对象后,直接file.size()就可以获取文件的大小,
if (request instanceof MultipartHttpServletRequest) {
MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
for (Iterator it = multipartHttpServletRequest.getFileNames(); it.hasNext();) {
String key = (String) it.next();
MultipartFile file = multipartHttpServletRequest.getFile(key);
String originalFilename = file.getOriginalFilename();
long size = file.getSize();//文件大小需要转换成KB或M
if (StringUtils.isNotBlank(originalFilename)) {
String suffixName = originalFilename.indexOf(".") == -1 ? "" : originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
try {
InputStream inputStream = file.getInputStream();
byte[] ToByteArray = FileCopyUtils.ToByteArray(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

阅读全文

与servlet大文件下载相关的资料

热点内容
怎么恢复系统文件 浏览:358
数据线转换器多少钱 浏览:274
美国队长qq皮肤多少钱 浏览:630
win8word文档在哪 浏览:180
甘肃省人事局文件在哪里 浏览:689
spss安装输入代码 浏览:546
网络语言知乎 浏览:596
iphoneicloud无法显示 浏览:112
ict程序包 浏览:729
java有哪些条件语句 浏览:345
冒险岛120级去哪里升级 浏览:511
手机输入法声音文件 浏览:876
下划线哪个app 浏览:48
win10h1z1切换桌面 浏览:911
js定义集合数组 浏览:153
win10企业关闭自动更新 浏览:920
js扩展对象 浏览:370
受控文件的章印内容怎么写 浏览:463
微信云文件丢失 浏览:299
手机bbc文件存在哪个路径 浏览:651

友情链接