jsp+Servlet 实现文件上传

笑着哭i 提交于 2020-02-01 04:18:53

首先导入上传文件的jar
在这里插入图片描述
上传页面 index.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
    <title>图书上传前预览</title>


    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">

    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>

    <style type="text/css">
        #pic{
            width:200px;
            height:200px;
            border-radius:5%;
            margin:20px auto;
            cursor: pointer;
        }
    </style>
</head>
<body>
<img align="middle" id="pic" src="images/preview.jpg">
<input id="upload" name="file" accept="image/*" type="file" style="display: none" />
点击图片,可以上传图片,并预览。 
<script type="text/javascript">
    $(function() {
        $("#pic").click(function() {
            $("#upload").click(); //隐藏了input:file样式后,点击头像就可以本地上传
            $("#upload").on("change", function() {
                var objUrl = getObjectURL(this.files[0]); //获取图片的路径,该路径不是图片在本地的路径
                if (objUrl) {
                    $("#pic").attr("src", objUrl); //将图片路径存入src中,显示出图片
                }
            });
        });
    });


    //建立一個可存取到該file的url
    function getObjectURL(file) {
        var url = null;
        if (window.createObjectURL != undefined) { // basic
            url = window.createObjectURL(file);
        } else if (window.URL != undefined) { // mozilla(firefox)
            url = window.URL.createObjectURL(file);
        } else if (window.webkitURL != undefined) { // webkit or chrome
            url = window.webkitURL.createObjectURL(file);
        }
        return url;
    }
</script>
</body>

</html>

Servlet处理页面 SmartUploadOne

package com.ambow.controller;
 
 
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
 
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
 
import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;
 
@WebServlet("/smartUploadOne.do")
public class SmartUploadOne extends HttpServlet {
 
 
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 
        //1. 设置上传文件保存路径
        String filePath = getServletContext().getRealPath("/") + "images";

        System.out.println(filePath);
        File file = new File(filePath);
        if (!file.exists()) {//判断文件夹,如果不存在,则自动创建
            file.mkdir();
        }

        //2.开始上传文件
        SmartUpload su = new SmartUpload();
        //初始化对象
        su.initialize(getServletConfig(), request, response);
        //设置上传文件大小
        su.setMaxFileSize(1024 * 1024 * 10);
        //设置所有文件的大小
        su.setTotalMaxFileSize(1024 * 1024 * 100);
        //设置允许上传文件类型
        su.setAllowedFilesList("jpg,gif,png");
        String result = "上传成功!";
        //设置禁止上传的文件类型

        String username = "";
        String imageurl = "";
        try {
            su.setDeniedFilesList("rar,jsp,js");
            //上传文件
            su.upload();

            //获取普通字段
            username = su.getRequest().getParameter("username");
            System.out.println(username);

            int count = su.save(filePath);
            System.out.println("上传成功" + count + "个文件!");
        } catch (Exception e) {
            result = "上传失败!";
            e.printStackTrace();
        }
 
        for (int i = 0; i < su.getFiles().getCount(); i++) {
            com.jspsmart.upload.File tempFile = su.getFiles().getFile(i);
            System.out.println("---------------------------");
            System.out.println("表单当中name属性值:" + tempFile.getFieldName());
            System.out.println("上传文件名:" + tempFile.getFieldName());
            System.out.println("上传文件长度:" + tempFile.getSize());
            System.out.println("上传文件的拓展名:" + tempFile.getFileExt());
            System.out.println("上传文件的全名:" + tempFile.getFilePathName());
            imageurl = tempFile.getFilePathName();
            System.out.println("---------------------------");
        }
 
        request.setAttribute("result", result);
        request.setAttribute("username",username);
        request.setAttribute("imageurl",imageurl);
        request.getRequestDispatcher("images.jsp").forward(request, response);
    }
 
 
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
 
 
}

上传完成后 可预览页面 images.jsp

<%--
  Created by IntelliJ IDEA.
  User: FoxBill
  Date: 2019/12/19 0019
  Time: 21:33
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>回显图片</title>
    <style type="text/css">
        div{
            width: 400px;
            margin: auto;
            background-color: bisque;
        }
    </style>
</head>
<body>
<h1 align="center">${result}</h1>
<div>
    <b>用户名:</b>${username}<br><br>
    <!--         /uploadImg/images/Hydrangeas.jpg               -->
    <b>图片的路径为:</b>${pageContext.request.contextPath}/images/${imageurl}<br><br>
    <img src="${pageContext.request.contextPath}/images/${imageurl}" width="200" height="200">
</div>
</body>
</html>

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!