servlet实现文件上传

来源:互联网 发布:武汉sdi矩阵 编辑:程序博客网 时间:2024/05/22 15:42

为了能够实现客户端向服务器上传文件,我们需要解决的问题需要从客户端和服务器来考虑:

1. 客户端即网页页面怎么实现文件的上传

2. 当客户端传来文件,服务器怎么接受,服务器接受了客户端传来的文件文件保存的哪里?如果很多用户上传,可能会产生多个文件出现同名的情况,这该则怎么解决。

 

客户端

对于客户端,解决方法很简单,我们依然使用form表单向服务器提交数据,但是和平时有有些许的不同

<form enctype="multipart/form-data" action="***"  method="post">

           <h3>请选择上传文件</h3>

           <input type="file" id="file" name="file"" />

          <input type="submit"  value="提交">

</form>

 

在这里我们可以看到,这个form表单多了enctype="multipart/form-data"这个属性,同时我们使用了 <inputtype="file"id="file"name="file""/>来提交我们的文件。到这里客户端就可以实现文件上传了。

 

服务器

对于服务器比较麻烦了,但是apache为我们文件的上传下载提供了一个工具包,我们可以用apache提供个我们的工具,方便的实现文件上传。我们需要的jar包如下:

<dependency>

         <groupId>commons-io</groupId>

         <artifactId>commons-io</artifactId>

         <version>2.4</version>

</dependency>

<dependency>

         <groupId>commons-fileupload</groupId>

         <artifactId>commons-fileupload</artifactId>

         <version>1.3.1</version>

</dependency>

 

接着就是实现我们的Servlet

publicclass FileUploadServletextends HttpServlet {

 

        //上传路径

        private FileuploadPath;

        //当文件过大时,需要设置一个临时路径

        private FiletempPath;

        @Override

        publicvoid doPost(HttpServletRequestreq, HttpServletResponseresp)throws ServletException, IOException {

                 //判断是否为上传文件的请求

                 if(!ServletFileUpload.isMultipartContent(req))

                         return;

                 //创建文件上传的工厂对象

                  DiskFileItemFactoryfactory =new DiskFileItemFactory();

                 //设置内存存储的最大值

                 factory.setSizeThreshold(4096);

                 //当文件过大时,设置将大于的部分放到临时文件夹

                 factory.setRepository(tempPath);

                 //创建ServletFileUpload对象,并将工厂对象传入

                  ServletFileUploadupload =new ServletFileUpload(factory);

                 //设置文件上传大小

                 upload.setSizeMax(20 * 1000000);

 

                 //使用上传对象从请求中得到表单中的元素

                 try {

                          List<FileItem>forms =upload.parseRequest(req);

 

                         for (FileItemitem :forms) {

 

                                  //如果为普通的表单域

                                  if (item.isFormField()) {

                                            Stringname =item.getFieldName();

                                           //解决普通输入项的数据的中文乱码问题

                                            Stringvalue =item.getString("UTF-8");

                                           // value = new String(value.getBytes("iso8859-1"),"UTF-8");

                                            System.out.println(name + "=" +value);

                                   }

                                  //如果为上传文件表单域

                                  else {

                                            StringfileName =item.getName();

                                           if(fileName == null ||fileName.trim().equals(""))

                                                    continue;

                                            /*注意:不同的浏览器提交的文件名是不一样的,有些浏览器提交上来的文件名是带有路径的, 如:c:\a\b\1.txt,而有些只是单纯的文件名,如:1.txt ,这里由于为了避免上传文件出现重名的情况,使用UUID随机生成文件名,取得上传文件的拓展名比如.txt .jpg等*/

                                            StringextName =fileName.substring(fileName.lastIndexOf("."));

                                           fileName = UUID.randomUUID().toString() +extName;

                                           

                                           //保存上传文件

                                            FileUtils.copyInputStreamToFile(item.getInputStream(),new File(uploadPath,fileName));

                                   }

                          }

 

                  }catch(FileUploadExceptione) {

                          e.printStackTrace();

                  }

         }

 

        //初始化设置文件上传路径和临时路径

        @Override

        publicvoid init()throwsServletException {

                  String upload = getServletContext().getRealPath("upload");

                  String temp = getServletContext().getRealPath("temp");

                  uploadPath = new File(upload);

                  tempPath = new File(temp);

                  if (!uploadPath.exists()) {

                          uploadPath.mkdir();

                  }

                  if (!tempPath.exists()){

                          tempPath.mkdir();

                  }

 

         }

}


转载自http://mp.weixin.qq.com/s?__biz=MzI3ODQzNTgyOQ==&mid=2247483752&idx=1&sn=ee20e0ef8329940c20a1c8df2922d73e#rd

0 0
原创粉丝点击