java eclipse 中文件的上传和下载示例解析

2020-10-08 0 501

文件的上传与下载(一)

在实现文件上传和下载之前我们需要做一些准备工作,在Apache官网去下载文件上传下载的两个组件,下载链接这里给出:common-fileupload组件下载:http://commons.apache.org/proper/commons-fileupload/

common-io组件下载:http://commons.apache.org/proper/commons-io/根据自己需求下载对应版本

一、创建工程

将所需要的两个开发包导入到工程项目中如图:

java eclipse 中文件的上传和下载示例解析

二、代码编写

1.前端页面代码

1). 在WebRoot目录下新建一个fileUpload.jsp页面,用来上传文件

<%@ page language=\"java\" import=\"java.util.*\" pageEncoding=\"GB18030\"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+\"://\"+request.getServerName()+\":\"+request.getServerPort()+path+\"/\";
%>

<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">
<html>
 <head>
 <base href=\"<%=basePath%>\">

 <title>My JSP \'fileUpload.jsp\' starting page</title>

 <meta http-equiv=\"pragma\" content=\"no-cache\">
 <meta http-equiv=\"cache-control\" content=\"no-cache\">
 <meta http-equiv=\"expires\" content=\"0\">
 <meta http-equiv=\"keywords\" content=\"keyword1,keyword2,keyword3\">
 <meta http-equiv=\"description\" content=\"This is my page\">
 <!--
 <link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\">
 -->

 </head>

 <body>
 <!-- 文件上传表单的提交方式必须是“post” 编码类型必须为:enctype=\"multipart/form-data\" -->
 <form action=\"UploadServlet\" method=\"post\" enctype=\"multipart/form-data\">

  username: <input type=\"text\" name=\"username\" /><br>
  file: <input type=\"file\" name=\"file\"><br>
  file2: <input type=\"file\" name=\"file2\"><br>
  <input type=\"submit\" value=\"上传文件\">

 </form>

 </body>
</html>

2).新建一个fileUploadResult.jsp页面用来显示结果信息

<%@ page language=\"java\" import=\"java.util.*,java.io.*\" pageEncoding=\"GB18030\"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+\"://\"+request.getServerName()+\":\"+request.getServerPort()+path+\"/\";
%>

<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">
<html>
 <head>
 <base href=\"<%=basePath%>\">

 <title>My JSP \'fileUploadResult.jsp\' starting page</title>

 <meta http-equiv=\"pragma\" content=\"no-cache\">
 <meta http-equiv=\"cache-control\" content=\"no-cache\">
 <meta http-equiv=\"expires\" content=\"0\">
 <meta http-equiv=\"keywords\" content=\"keyword1,keyword2,keyword3\">
 <meta http-equiv=\"description\" content=\"This is my page\">
 <!--
 <link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\">
 -->

 </head>

 <body>
 <%--
 <%
  //获取流对象
  InputStream inputStream = request.getInputStream();

  BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

  String buffer = null;

  while((buffer = br.readLine()) != null){
   out.print(buffer + \"<br>\");
  }

  br.close();
  inputStream.close();

  %>
  --%>
  ${message}<br>

  EL-username : ${requestScope.username} <br>
  EL-file1 : ${requestScope.file }<br>
  EL-file2 : ${requestScope.file2}<br>

 </body>
</html>

2. 编写上传文件处理的Servlet代码

1) UploadServlet.java代码如下:

package com.Servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
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;

public class UploadServlet extends HttpServlet {

 /**
  * The doPost method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to post.
  *
  * @param request the request send by the client to the server
  * @param response the response send by the server to the client
  * @throws ServletException if an error occurred
  * @throws IOException if an error occurred
  */
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {


  //得到上传文件的保存目录,将上传的文件放在webRoot目录下(但是一般为了安全放在WEB-INF目录下,不允许外界直接访问,保证上传的安全)
  String path = this.getServletContext().getRealPath(\"/upload\");

  File file = new File(path);

  //判断上传文件的保存目录是否存在
  if(!file.exists() && !file.isDirectory()){
   System.out.println(path + \"目录不存在,需要创建!\");
   //创建目录
   file.mkdir();
  }
  //消息提示
  String message = \"\";
  try{
   //使用Apache文件上传组件处理文件上传步骤:
   //1.创建一个DiskFileItemFactory工厂
   DiskFileItemFactory factory = new DiskFileItemFactory();
   //2.创建一个文件上传解析器
   ServletFileUpload upload = new ServletFileUpload(factory);
   //解决中文乱码
   upload.setHeaderEncoding(\"UTF-8\");
   //3.判断提交的数据普通表单的数据还是带文件上传的表单
   if(!upload.isMultipartContent(request)){
    //如果是表单数据普通表单,则按照传统方式获取数据
    return ;
   }
   //4.使用ServletFileUpload解析器解析上传数据,解析结果返回的是一个List<FileItem>集合,每一个FileItem对应一个Form表单的输入项
   List<FileItem> list = upload.parseRequest(request);
   for(FileItem item : list){
    //如果fileItem中封装的是普通输入项的数据
    if(item.isFormField()){
     //获取字段名字
     String name = item.getFieldName();
     //解决普通输入项中中文乱码问题
     String value = item.getString(\"UTF-8\");//value = new String(value.getBytes(\"iso8859-1\"),\"UTF-8\");
     System.out.println(name + \" = \" + value);
    }else{ //如果表单中提交的是上传文件
     //获得上传的文件名称
     String filename = item.getName();
     System.out.println(filename);
     if(filename == null || filename.trim().equals(\" \")){
      continue;
     }
     //注意:不同的浏览器提交的文件名称是不一样的,有些浏览器提交的文件会带有路径,如“D:\\\\project\\WebRoot\\hello.jsp”,有一些是单纯的文件名:hello.jsp
     //去掉获取到文件名中的路径名,保留单纯的文件名
     filename = filename.substring(filename.lastIndexOf(\"\\\\\") + 1);
     //获取item中的上传文件的输入流
     InputStream in = item.getInputStream();
     //创建一个文件输入流
     FileOutputStream out = new FileOutputStream(path + \"\\\\\" + filename);
     //创建一个缓冲区
     byte buffer[] = new byte[1024];
     //判断输入流中的数据是否已经读取完毕的标志位
     int len = 0;
     //循环将输入流读入到缓冲区当中,(len = in.read(buffer)>0)就表示in里面还有数据存在
     while((len = in.read(buffer)) > 0){
      //使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(path+\"\\\\\"+filename)当中
      out.write(buffer, 0, len);
     }
     //关闭输入流
     in.close();
     //关闭输出流
     out.close();
     //删除处理文件上传生成的临时文件
     item.delete();
     message = \"文件上传成功!\";


    }
   }

  }catch(Exception e){
   message = \"文件上传失败!\";
   e.printStackTrace();
  }

  request.setAttribute(message, message);
  request.getRequestDispatcher(\"fileUploadResult.jsp\").forward(request, response);

 }

}

2)web.xml文件中的配置

<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<web-app version=\"3.0\"
 xmlns=\"http://java.sun.com/xml/ns/javaee\"
 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
 xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd\">
 <servlet>

 <servlet-name>UploadServlet</servlet-name>
 <servlet-class>com.Servlet.UploadServlet</servlet-class>
 </servlet>

 <servlet-mapping>
 <servlet-name>UploadServlet</servlet-name>
 <url-pattern>/UploadServlet</url-pattern>
 </servlet-mapping>

</web-app>

结果:

java eclipse 中文件的上传和下载示例解析

java eclipse 中文件的上传和下载示例解析

到此这篇关于eclipse java中文件的上传和下载示例解析的文章就介绍到这了,更多相关eclipse java中文件的上传和下载内容请搜索自学编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持自学编程网!

遇见资源网 JAVA java eclipse 中文件的上传和下载示例解析 http://www.ox520.com/19555.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务