欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JavaWeb文件上传与下载功能解析

程序员文章站 2024-03-13 08:48:03
在开发过程中文件的上传下载很常用。这里简单的总结一下: 1.文件上传必须满足的条件: a、 页面表单的method必须是post 因为get传送的数据太小了 b、...

在开发过程中文件的上传下载很常用。这里简单的总结一下:

1.文件上传必须满足的条件:
a、 页面表单的method必须是post 因为get传送的数据太小了
b、 页面表单的enctype必须是multipart/form-data类型的
c、 表单中提供上传输入域
代码细节: 客户端表单中:<form enctype="multipart/form-data"/>
(如果没有这个属性,则服务端读取的文件路径会因为浏览器的不同而不同)
服务端servletinputstream is=request.getinputstream();用流的方式获取请求正文内容,进一步的解析。

JavaWeb文件上传与下载功能解析

2.上传文件的细节:
(1)为什么设置表单类型为:multipart/form-data.是设置这个表单传递的不是key=value值。传递的是字节码.
表单与请求的对应关系:

JavaWeb文件上传与下载功能解析

如上可以看出在设置表单类型为:multipart/form-data之后,在http请求体中将你选择的文件初始化为二进制,如上图中的cookie之下的一串的随机字符串下的内容。
但注意,在标识文件(即一串随机字符串)所分割出来的文件字节码中有两行特殊字符,即第一行内容文件头和一行空行。之后的第三行才是二进制的文件内容。
所以在服务端接受客户端上传的文件时,获取http请求参数中的文件二进制时,要去掉前三行。

3.自己手工解析上传的txt文件:

import java.io.bufferedreader;
import java.io.ioexception;
import java.io.inputstream;
import java.io.inputstreamreader;
import java.io.printwriter;
import javax.servlet.servletexception;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
/**
 * 如果一个表单的类型是post且enctype为multipart/form-date
 * 则所有数据都是以二进制的方式向服务器上传递。
 * 所以req.getparameter("xxx")永远为null。
 * 只可以通过req.getinputstream()来获取数据,获取正文的数据
 * 
 * @author wangxi
 *
 */
public class upservlet extends httpservlet {
 public void dopost(httpservletrequest req, httpservletresponse resp)
   throws servletexception, ioexception {
  req.setcharacterencoding("utf-8");
  string txt = req.getparameter("txt");//返回的是null
  system.err.println("txt is :"+txt);
  system.err.println("=========================================");
  inputstream in = req.getinputstream();
//  byte[] b= new byte[1024];
//  int len = 0;
//  while((len=in.read(b))!=-1){
//   string s = new string(b,0,len);
//   system.err.print(s);
//  }
  bufferedreader br = new bufferedreader(new inputstreamreader(in));
  string firstline = br.readline();//读取第一行,且第一行是分隔符号,即随机字符串
  string filename = br.readline();//第二行文件信息,从中截取出文件名
  filename = filename.substring(filename.lastindexof("\\")+1);// xxxx.txt"
  filename = filename.substring(0,filename.length()-1);

  br.readline();
  br.readline();
  string data = null;
  //获取当前项目的运行路径
  string projectpath = getservletcontext().getrealpath("/up");
  printwriter out = new printwriter(projectpath+"/"+filename);
  while((data=br.readline())!=null){
   if(data.equals(firstline+"--")){
    break;
   }
   out.println(data);
  }
  out.close();
 }
}

4.使用apache-fileupload处理文件上传:
框架:是指将用户经常处理的业务进行一个代码封装。让用户可以方便的调用。
目前文件上传的(框架)组件:
apache—-fileupload -
orialiy – cos – 2008() -
jsp-smart-upload – 200m。
用fileupload上传文件:

需要导入第三方包:

    apache-fileupload.jar – 文件上传核心包。
    apache-commons-io.jar – 这个包是fileupload的依赖包。同时又是一个工具包。

核心类:

    diskfileitemfactory – 设置磁盘空间,保存临时文件。只是一个具类。
    servletfileupload  - 文件上传的核心类,此类接收request,并解析reqeust。
    servletfileupload.parserequest(requdest)  - list<fileitem>
    注:一个fileitem就是一个标识的开始:---------243243242342 到 ------------------245243523452—就是一个fileitem

第一步:导入包:

JavaWeb文件上传与下载功能解析

第二步:书写一个servlet完成dopost方法

/**
 * diskfileitemfactory构造的两个参数
 * 第一个参数:sizethreadhold - 设置缓存(内存)保存多少字节数据,默认为10k
 * 如果一个文件没有大于10k,则直接使用内存直接保存成文件就可以了。
 * 如果一个文件大于10k,就需要将文件先保存到临时目录中去。
 * 第二个参数 file 是指临时目录位置
 *
 */
public class up2servlet extends httpservlet {
 public void dopost(httpservletrequest req, httpservletresponse resp)
   throws servletexception, ioexception {
  req.setcharacterencoding("utf-8");
  //获取项目的路径
  string path = getservletcontext().getrealpath("/up");
  //第一步声明diskfileitemfactory工厂类,用于在指的磁盘上设置一个临时目录
  diskfileitemfactory disk = 
    new diskfileitemfactory(1024*10,new file("/home/wang/"));
  //第二步:声明servletfileupoload,接收上面的临时目录
  servletfileupload up = new servletfileupload(disk);
  //第三步:解析request
  try {
   list<fileitem> list = up.parserequest(req);
   //如果就一个文件
   fileitem file = list.get(0);
   //获取文件名,带路径
   string filename = file.getname();
   filename = filename.substring(filename.lastindexof("\\")+1);
   //获取文件的类型
   string filetype = file.getcontenttype();
   //获取文件的字节码
   inputstream in = file.getinputstream();
   //声明输出字节流
   outputstream out = new fileoutputstream(path+"/"+filename);
   //文件copy
   byte[] b = new byte[1024];
   int len = 0;
   while((len=in.read(b))!=-1){
    out.write(b,0,len);
   }
   out.close();

   long size = file.getinputstream().available();

   //删除上传的临时文件
   file.delete();
   //显示数据
   resp.setcontenttype("text/html;charset=utf-8");
   printwriter op = resp.getwriter();
   op.print("文件上传成功<br/>文件名:"+filename);
   op.print("<br/>文件类型:"+filetype);
   op.print("<br/>文件大小(bytes)"+size);



  } catch (exception e) {
   e.printstacktrace();
  }

 }

}

5.使用该框架上传多个文件:

第一步:修改页面的表单为多个input type=”file”

<form action="<c:url value='/up3servlet'/>" method="post" enctype="multipart/form-data">
  file1:<input type="file" name="txt"><br/>
  file2:<input type="file" name="txt"><br/>
  <input type="submit"/>
 </form>

第二步:遍历list

public class up3servlet extends httpservlet {
 public void dopost(httpservletrequest request, httpservletresponse response)
   throws servletexception, ioexception {
  request.setcharacterencoding("utf-8");
  string path = getservletcontext().getrealpath("/up");
  //声明disk
  diskfileitemfactory disk = new diskfileitemfactory();
  disk.setsizethreshold(1024*1024);
  disk.setrepository(new file("d:/a"));
  //声明解析requst的servlet
  servletfileupload up = new servletfileupload(disk);
  try{
   //解析requst
   list<fileitem> list = up.parserequest(request);
   //声明一个list<map>封装上传的文件的数据
   list<map<string,string>> ups = new arraylist<map<string,string>>();
   for(fileitem file:list){
    map<string,string> mm = new hashmap<string, string>();
    //获取文件名
    string filename = file.getname();
    filename = filename.substring(filename.lastindexof("\\")+1);
    string filetype = file.getcontenttype();
    inputstream in = file.getinputstream();
    int size = in.available();
    //使用工具类
    fileutils.copyinputstreamtofile(in,new file(path+"/"+filename));
    mm.put("filename",filename);
    mm.put("filetype",filetype);
    mm.put("size",""+size);

    ups.add(mm);
    file.delete();
   }
   request.setattribute("ups",ups);
   //转发
   request.getrequestdispatcher("/jsps/show.jsp").forward(request, response);

  }catch(exception e){
   e.printstacktrace();
  }
 }
}

如上就是上传文件的常用做法。现在我们在来看看fileupload的其他查用api.

 JavaWeb文件上传与下载功能解析

JavaWeb文件上传与下载功能解析

判断一个fileitem是否是file(type=file)对象或是text(type=text|checkbox|radio)对象:
boolean isformfield() 如果是text|checkbox|radio|select这个值就是true.

6.处理带说明信息的图片

JavaWeb文件上传与下载功能解析

public class updescservlet extends httpservlet {
 public void dopost(httpservletrequest request, httpservletresponse response)
   throws servletexception, ioexception {
  request.setcharacterencoding("utf-8");//可以获取中文的文件名
  string path = getservletcontext().getrealpath("/up");
  diskfileitemfactory disk = 
    new diskfileitemfactory();
  disk.setrepository(new file("d:/a"));
  try{
   servletfileupload up = 
     new servletfileupload(disk);
   list<fileitem> list = up.parserequest(request);
   for(fileitem file:list){
    //第一步:判断是否是普通的表单项
    if(file.isformfield()){
     string filename = file.getfieldname();//<input type="text" name="desc">=desc
     string value = file.getstring("utf-8");//默认以iso方式读取数据
     system.err.println(filename+"="+value);
    }else{//说明是一个文件
     string filename = file.getname();
     filename = filename.substring(filename.lastindexof("\\")+1);
     file.write(new file(path+"/"+filename));
     system.err.println("文件名是:"+filename);
     system.err.println("文件大小是:"+file.getsize());
     file.delete();
    }
   }
  }catch(exception e){
   e.printstacktrace();
  }
 }

}

7.文件上传的性能提升
在解析request获取fileitem的集合的时候,使用:

fileitemiterator it= up.getitemiterator(request);

比使用

list<fileitem> list = up.parserequest(request);

性能上要好的多。
示例代码:

public class fastservlet extends httpservlet {


 public void dopost(httpservletrequest request, httpservletresponse response)
   throws servletexception, ioexception {
  request.setcharacterencoding("utf-8");
  string path = getservletcontext().getrealpath("/up");
  diskfileitemfactory disk = 
    new diskfileitemfactory();
  disk.setrepository(new file("d:/a"));
  try{
   servletfileupload up = new servletfileupload(disk);
   //以下是迭代器模式
   fileitemiterator it= up.getitemiterator(request);
   while(it.hasnext()){
    fileitemstream item = it.next();
    string filename = item.getname();
    filename=filename.substring(filename.lastindexof("\\")+1);
    inputstream in = item.openstream();
    fileutils.copyinputstreamtofile(in,new file(path+"/"+filename));
   }
  }catch(exception e){
   e.printstacktrace();
  }

 }

}

8.文件的下载
既可以是get也可以是post。

public void dopost(httpservletrequest req, httpservletresponse resp)
   throws servletexception, ioexception {
  req.setcharacterencoding("utf-8");
  string name = req.getparameter("name");
  //第一步:设置响应的类型
  resp.setcontenttype("application/force-download");
  //第二读取文件
  string path = getservletcontext().getrealpath("/up/"+name);
  inputstream in = new fileinputstream(path);
  //设置响应头
  //对文件名进行url编码
  name = urlencoder.encode(name, "utf-8");
  resp.setheader("content-disposition","attachment;filename="+name);
  resp.setcontentlength(in.available());

  //第三步:开始文件copy
  outputstream out = resp.getoutputstream();
  byte[] b = new byte[1024];
  int len = 0;
  while((len=in.read(b))!=-1){
   out.write(b,0,len);
  }
  out.close();
  in.close();
 }

在使用j2ee流行框架时

使用框架内部封装好的来完成上传下载更为简单:

struts2完成上传.

在使用struts2进行开发时,导入的jar包不难发现存在 commons-fileupload-1.3.1.jar 包。通过上面的学习我们已经可以使用它进行文件的上传下载了。但struts2在进行了进一步的封装。

view

<form action="fileupload.action" method="post" enctype="multipart/form-data">
   
  username: <input type="text" name="username"><br>
  file: <input type="file" name="file"><br>

  <input type="submit" value="submit">
 </form>

controller

public class fileuploadaction extends actionsupport
{
 private string username;

   //注意,file并不是指前端jsp上传过来的文件本身,而是文件上传过来存放在临时文件夹下面的文件
 private file file;

 //提交过来的file的名字
 //struts会自动截取上次文件的名字注入给该属性
 private string filefilename;
 //getter和setter此时为了节约篇幅省掉
  @override
 public string execute() throws exception
 {
 //保存上传文件的路径
  string root = servletactioncontext.getservletcontext().getrealpath("/upload");
  //获取临时文件输入流
  inputstream is = new fileinputstream(file);
  //输出文件
  outputstream os = new fileoutputstream(new file(root, filefilename));
  //打印出上传的文件的文件名
  system.out.println("filefilename: " + filefilename);
    // 因为file是存放在临时文件夹的文件,我们可以将其文件名和文件路径打印出来,看和之前的filefilename是否相同
  system.out.println("file: " + file.getname());
  system.out.println("file: " + file.getpath());

  byte[] buffer = new byte[1024];
  int length = 0;

  while(-1 != (length = is.read(buffer, 0, buffer.length)))
  {
   os.write(buffer);
  }

  os.close();
  is.close();

  return success;
 }
}

首先我们要清楚一点,这里的file并不是真正指代jsp上传过来的文件,当文件上传过来时,struts2首先会寻找struts.multipart.savedir(这个是在default.properties里面有)这个name所指定的存放位置(默认是空),我们可以在我们项目的struts2中来指定这个临时文件存放位置。

 <constant name="struts.multipart.savedir" value="/repository"/> 

 如果没有设置struts.multipart.savedir,那么将默认使用javax.servlet.context.tempdir指定的地址,javax.servlet.context.tempdir的值是由服务器来确定的,例如:假如我的web工程的context是abc,服务器使用tomcat,那么savepath就应该是%tomcat_home%/work/catalina/localhost/abc_,临时文件的名称类似于upload__1a156008_1373a8615dd__8000_00000001.tmp,每次上传的临时文件名可能不同,但是大致是这种样式。而且如果是使用eclipse中的servers里面配置tomcat并启动的话,那么上面地址中的%tomcat_home%将不会是系统中的实际tomcat根目录,而会是eclipse给它指定的地址,例如我本地的地址是这样的:/home/wang/eclipsejavacode/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/work/catalina/localhost/abc/upload__1a156008_1373a8615dd__8000_00000001.tmp。

struts2完成下载.

struts2的文件下载更简单,就是定义一个输入流,然后将文件写到输入流里面就行,关键配置还是在struts.xml这个配置文件里配置:

public class filedownloadaction extends actionsupport
{
 //要下载文件在服务器上的路径
 private string path;
 //要下载文件的文件名
 private string downloadfilename;
 //写入getter和setter
 public inputstream getdownloadfile()
 {
  return servletactioncontext.getservletcontext().getresourceasstream(path);
 }

 @override
 public string execute() throws exception
 {
 //当前action默认在valuestack的栈顶
  setdownloadfilename(xxx);
  return success;
 }
}

action只是定义了一个输入流downloadfile,然后为其提供getter方法就行,接下来我们看看struts.xml的配置文件:

 <action name="filedownload" class="com.struts2.filedownloadaction">
    <result name="download" type="stream">
  <param name="contentdisposition">attachment;filename="${downloadfilename}"</param>
  <param name="inputname">downloadfile</param>
   </result>
 </action>

struts.xml配置文件有几个地方我们要注意,首先是result的类型,type一定要定义成stream类型_,告诉action这是文件下载的result,result元素里面一般还有param子元素,这个是用来设定文件下载时的参数,inputname这个属性就是得到action中的文件输入流,名字一定要和action中的输入流属性名字相同,然后就是contentdisposition属性,这个属性一般用来指定我们希望通过怎么样的方式来处理下载的文件,如果值是attachment,则会弹出一个下载框,让用户选择是否下载,如果不设定这个值,那么浏览器会首先查看自己能否打开下载的文件,如果能,就会直接打开所下载的文件,(这当然不是我们所需要的),另外一个值就是filename这个就是文件在下载时所提示的文件下载名字。在配置完这些信息后,我们就能过实现文件的下载功能了。

springmvc完成上传:

view于struts2示例中的完全一样。此出不在写出。

controller:

@controller
@requestmapping(value="fileoperate")
public class fileoperateaction {
 @requestmapping(value="upload")
 public string upload(httpservletrequest request,@requestparam("file") multipartfile photofile){
 //上传文件保存的路径
  string dir = request.getsession().getservletcontext().getrealpath("/")+"upload";
  //原始的文件名
  string filename = photofile.getoriginalfilename();      //获取文件扩展名
  string extname = filename.substring(filename.lastindexof(".")); 
 //防止文件名冲突,把名字小小修改一下
 filename = filename.substring(0,filename.lastindexof(".")) + system.nanotime() + extname; 
  fileutils.writebytearraytofile(new file(dir,filename),photofile.getbytes());
  return "success";
 }
 }

springmvc完成下载:

 @requestmapping("/download")
 public string download(string filename, httpservletrequest request,
   httpservletresponse response) {
  response.setcharacterencoding("utf-8");
  response.setcontenttype("multipart/form-data");
  response.setheader("content-disposition", "attachment;filename="
    + filename);
  try {
   inputstream inputstream = new fileinputstream(new file(文件的路径);

   outputstream os = response.getoutputstream();
   byte[] b = new byte[2048];
   int length;
   while ((length = inputstream.read(b)) > 0) {
    os.write(b, 0, length);
   }

    // 这里主要关闭。
   os.close();

   inputstream.close();
  } catch (filenotfoundexception e) {
   e.printstacktrace();
  } catch (ioexception e) {
   e.printstacktrace();
  }
   // 返回值要注意,要不然就出现下面这句错误!
   //java+getoutputstream() has already been called for this response
  return null;
 }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。