文件的上传下载


一、前提准备

1. 添加jspSmartUpload.jar

这个jar包在maven repository 仓库里是找不到,需要自己从本地添加。你需要在WEB-INF下创建lib文件夹,然后把jar包复制到lib文件夹下。然后在pom.xml下添加如下依赖:

 <!--文件上传下载的依赖-->
        <dependency>
            <groupId>jspSmartUpload</groupId>
            <artifactId>jspSmartUpload</artifactId>
            <version>1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/jspSmartUpload.jar</systemPath>
        </dependency>

在网上查的其他人上传下载用的是SmartUpload.jar,但配置是一样的,我猜应该只是文件名字不同。

二、上传下载的实现

1. Register.jsp

这里需要注意的是文件上传,表单必须设置 method="post"enctype="multipart/form-data"multipart/form-data,是不对字符编码,在使用包含文件上传控件的表单时,必须使用该值。文件的上传是通过 <input type="file"> 这个标签实现的。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set value="${pageContext.request.contextPath}" var="path"></c:set>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <div>
        <label>用户名</label>
        <input type="text" name="uname">
    </div>
    <form action="${path}/RegisterServlet" method="post" enctype="multipart/form-data">
        <div>
            <label>选择图片</label><br><br>
            <input type="file" name="img1">
            <input type="file" name="img2">
            <input type="file" name="img3">
        </div><br>
        <input type="submit" value="上传">
    </form>
</body>
</html>

2. UploadServlet

Register.jsp 提交过来的文件,进行上传。步骤如下:

  1. SmartUpload对象创建初始化
    ①创建:SmartUpload su = new SmartUpload();
    ②初始化:su.initialize(getServletConfig(), request, response);
  2. 设置上传路径文件类型文件大小
    ①上传路径:String path = “D:/upload”;
    ②文件类型:su.setAllowedFilesList(“jpg,gif,bmp,png”);
    ③单个文件最大值:su.setMaxFileSize(1024 * 1024 * 5);
  3. 文件上传。文件的上传是以单个文件的形式上传的。步骤:
    ①上传准备:su.upload();
    ②获取上传文件的数量:int count = su.getFiles().getCount();
    ③获取每一个要上传的文件:File file = su.getFiles().getFile(i);
    ④保存文件到某路径:file.saveAs(path + “/” + file.getFileName());
package com.servlet;

import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "RegisterServlet", value = "/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        SmartUpload su = new SmartUpload();
        su.initialize(getServletConfig(), request, response);
        su.setMaxFileSize(1024 * 1024 * 5);
        su.setAllowedFilesList("jpg,gif,bmp,png");
        String path = "D:/upload";

        List<String> fileNames = new ArrayList<>();
        try {
            su.upload();
            int count = su.getFiles().getCount();
            for (int i=0; i < count; i++) {
                File file = su.getFiles().getFile(i);
                // 文件大小为0,就不下载了
                if (file.getSize() == 0) {
                    continue;
                }
                file.saveAs(path + "/" + file.getFileName());
                fileNames.add(file.getFileName());
            }
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }
        System.out.println("图片上传成功!");
        // 将文件名传递给Success.jsp页面
        request.setAttribute("fileNames", fileNames);
        request.getRequestDispatcher("Success.jsp").forward(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

3. Success.jsp

上传成功后的页面,用来显示上传成功的图片和图片的名称和下载地址。注意这里显示图片的路径 D:/upload/${fileName}需要在服务器配置虚拟路径,否则在服务器上是无法获取到该路径的。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set value="${pageContext.request.contextPath}" var="path"></c:set>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <c:forEach items="${fileNames}" var="fileName">
    	<!--图片显示-->
        <img alt="${fileName}" src="D:/upload/${fileName}">
        <!--图片名字-->
        <h1>${fileName}</h1>
        <!--图片下载-->
        <a href="${path}/LoadServlet?fileName=${fileName}">下载图片</a>
    </c:forEach>
</body>
</html>

4. DownloadServlet

点击下载图片的链接后,下载请求发送到该页面。获取到要下载文件的名字,查询到该图片如果存在的话,就执行下载操作。

  1. SmartUpload对象创建初始化
    ①创建:SmartUpload su = new SmartUpload();
    ②初始化:su.initialize(getServletConfig(), request, response);
  2. 设置下载路径
    ①获取文件名:String path = request.getParameter(“fileName”);
    ②设置下载路径:path = “D:/upload/” + path;
  3. 下载文件
    ①根据文件路径下载文件:su.downloadFile(path);
package com.servlet;

import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "LoadServlet", value = "/LoadServlet")
public class LoadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getParameter("fileName");
        SmartUpload su = new SmartUpload();
        su.initialize(getServletConfig(), request, response);
        path = "D:/upload/" + path;
        // 禁止浏览器下载后自动打开资源
        su.setContentDisposition(null);
        try {
            // 根据文件路径下载文件
            su.downloadFile(path);
        } catch (SmartUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ServletException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

总结

本文分享了如何实现文件的上传下载。主要是需要SmartUpload这个类,使用类里封装的方法分别实现文件上传,文件下载。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员_动次动次

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

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

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

打赏作者

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

抵扣说明:

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

余额充值