[Java 基础]-- 纯servlet实现文件上传和下载文件

Java 专栏收录该内容
137 篇文章 6 订阅

一、准备材料

1、apache提供的包,效率高,且实用性强:

  ( 1)、commons-fileupload-1.3.1.jar

   (2)、commons-io-2.4.jar

2、 jdk1.6以上

 

二、上传实现的代码

 1、upload.jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>


<html>

  <head>

    <base href="<%=basePath%>">

    <title>My JSP 'index.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">
  </head>
  <body>

<form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data">

<!--enctype属性值的意义-->

    <input type="file" name="myfile">
    <input type="text" name="mytext" value="123456"/>

    <input type="text" name="mytext" value="123456"/>

    <input type="submit" value="确认上传">

    </form>

  </body>

</html>

 

application/x-www-form-urlencoded在发送前对所有字符进行编码(默认)。
multipart/form-data不对字符编码。当使用有文件上传控件的表单时,该值是必需的。
text/plain将空格转换为 "+" 符号,但不编码特殊字符。

2、servlet代码

package com.test.upload;



import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.HttpRetryException;

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.FileItemFactory;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;



@SuppressWarnings("serial")

public class UploadServerlt extends HttpServlet {

public void service(HttpServletRequest request, HttpServletResponse response)

throws HttpRetryException, IOException {

try {

//解析http请求

boolean isMultipart = ServletFileUpload.isMultipartContent(request);

//解析成功

if (isMultipart == true) {

// 获得磁盘文件条目工厂

FileItemFactory factory = new DiskFileItemFactory();

// 高水平的API文件上传处理,将文件保存在服务器硬盘

ServletFileUpload upload = new ServletFileUpload(factory);

//设置上传的单个文件的大小6M

upload.setSizeMax(6*1024*1024);

//设置上传的总文件的大小40M

upload.setFileSizeMax(40*1024*1024);

//http中的复杂表单元素都被看作是FileItem,所以可以上传多个文件

List<FileItem> fileItemList = upload.parseRequest(request);

//如果表单内容不为空

if (fileItemList != null) {

//遍历内容

for (FileItem fileItem: fileItemList) {

//如果是字符:<input type="text" name="mytext" value="123456"/>

if (fileItem.getFieldName().equalsIgnoreCase("mytext")) {

String text2 = fileItem.getString();

}

//如果是文件:<input type="file" name="myfile">

if (fileItem.getFieldName().equalsIgnoreCase("myfile")) {

InputStream in = fileItem.getInputStream();

//写入指定目录下

FileOutputStream fos = new FileOutputStream("F:/232.zip");

byte[] buffer = new byte[1024];

int length;

while ((length = in.read(buffer)) != -1) {

fos.write(buffer, 0, length);

}

in.close();

fos.close();

//清除应用服务器下的临时文件

fileItem.delete();

}

}

}

request.getRequestDispatcher("/index.jsp").forward(request,response);

}

} catch (Exception e) {

e.printStackTrace();

try {

request.getRequestDispatcher("/error.jsp").forward(request,response);

} catch (ServletException e1) {

e1.printStackTrace();

}

}

}

}

3、web.xml文件

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.5" 

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_2_5.xsd">

  <welcome-file-list>

    <welcome-file>index.jsp</welcome-file>

  </welcome-file-list>

  <!-- 测试上传文件 -->

  <servlet>

  <servlet-name>Upload</servlet-name>

  <servlet-class>com.test.upload.UploadServerlt</servlet-class>

  </servlet>

  <servlet-mapping>

  <servlet-name>Upload</servlet-name>

  <url-pattern>/upload</url-pattern>

  </servlet-mapping>

</web-app>

 

4、访问地址:http://localhost:8080/TestServer/jsp/upload.jsp

5、点击后成功

三、实现下载的代码

1、DownFileServlet.java

package com.test.downFile;

 

import java.io.FileInputStream;

import java.io.IOException;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

@SuppressWarnings("serial")

public class DownFileServlet extends HttpServlet{

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

//获取下载的文件名称

String downPath=(String)request.getParameter("downPath");

try {

//通过response响应返回给客户端

response.setHeader("Content-Disposition","attachment;filename=\""+new String (downPath.getBytes("GBK"),"ISO8859-1")+"\"");//文件名称

//开始写给客户端

FileInputStream fis=new FileInputStream("F://"+downPath);//注意正则表达式的冲突,所以使用//

byte b[]=new byte[1024];

int length;

while((length=fis.read(b))>0){

response.getOutputStream().write(b,0,length);

}

fis.close();

response.getOutputStream().flush();//最好加上这句话,否则缓存会存在

} catch (Exception e) {

e.printStackTrace();

}

}

}

2.downFile.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<html>

  <head>

    <base href="<%=basePath%>">

    

    <title>My JSP 'index.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">

  </head>

  <body>

    <form action="${pageContext.request.contextPath}/downFile" method="post" >

    <!-- 指定路径,实际的项目中应该是从数据库中获取 -->

    <input type="text" name="downPath" value="img.zip"/>

    <input type="submit" value="点击下载">

    </form>

  </body>

</html>

3、web.xml文件配置

<!-- 测试下载文件 -->

  <servlet>

  <servlet-name>DownFile</servlet-name>

  <servlet-class>com.test.downFile.DownFileServlet</servlet-class>

  </servlet>

  <servlet-mapping>

  <servlet-name>DownFile</servlet-name>

  <url-pattern>/downFile</url-pattern>

  </servlet-mapping>

  • 0
    点赞
  • 0
    评论
  • 5
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

©️2022 CSDN 皮肤主题:Age of Ai 设计师:meimeiellie 返回首页

打赏作者

highfei2011

你的鼓励将是我创作的最大动力!

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值