MyQuan

基于javaweb的临时文件中转站
前言 今天在机房敲代码时,旁边同学需要一个很小的文件,我有。由于机房没有安装什么传文件的程序,只能是用U盘对拷咯。...
扫描右侧二维码阅读全文
02
2019/04

基于javaweb的临时文件中转站

前言

今天在机房敲代码时,旁边同学需要一个很小的文件,我有。由于机房没有安装什么传文件的程序,只能是用U盘对拷咯。
个人不是插拔U盘,而且要是这个是没有U盘就更麻烦了。所以一怒之下写了这个文件中转站。
项目地址:

正文

环境

  • window 10
  • Java jdk1.8
  • Tomcat 9.0
  • IDE: Eclipse

代码

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@page import="look.look"%>
    <%@page import="java.util.ArrayList"%>
    <%@page import="java.util.Iterator"%>
<!doctype html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件上传</title>
    <link rel="stylesheet" type="text/css" href="css/reset.css">
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/default.css">
    <link rel="stylesheet" type="text/css" href="css/jquery.filer.css">
    <link rel="stylesheet" type="text/css" href="css/jquery.filer-dragdropbox-theme.css">
    <link rel="stylesheet" type="text/css" href="css/tomorrow.css">
    <link rel="stylesheet" type="text/css" href="css/custom.css">
    <!--[if IE]>
        <script src="http://libs.useso.com/js/html5shiv/3.7/html5shiv.min.js"></script>
    <![endif]-->
</head>
<body>
    <br><br>
    <center>
        <h3>临时文件中转</h3>
        <p>文件上传后请尽快删除!本网站不保证任何文件的安全!</p>
        <p>最大文件支持200MB!</p>
        <a href="https://www.myelf.club">@MY ELF</a>
        <hr>
    </center>
    <br><br>
    <article class="container">
         <div class="row">
             <div class="col-md-12 upbox">
                 <form action="up" method="post" enctype="multipart/form-data" class="text-center">
                     <input type="file" name="files[]" id="demo-fileInput-4" multiple="multiple">
                     <input type="submit" class="btn-custom green" value="上传">
                 </form>
             </div>
          </div>
    </article>
    <%look all=new look(); 
    ArrayList<String> str=new ArrayList<String>(); 
    str=all.look();
    Iterator<String> astr=str.iterator();
    %>
    <div class="container">      
      <table class="table table-hover">
      <h2>文件列表</h2>
        <thead>
          <tr>
            <th width="90%">文件名</th>
            <th style="text-align: center" width="5%"></th>
            <th width="5%"></th>
          </tr>
        </thead>
        <tbody>
        <%while(astr.hasNext()){String ss=astr.next();%>
          <tr>
            <td style="font-size: 16px;padding-top: 15px"><%=ss %></td>
            <td style="text-align: center"><a href="<%="../upload/"+ss%>" download style="text-align: center" class="btn-custom green">下载</a></td>
            <td style="text-align: center">
                <form action="delete" method="post" class="text-center">
                <button type="submit" name="filename" class="btn-custom red" style="text-align: center" value="<%=ss%>">删除</button>
                </form>
            </td>
          </tr>
          <%} %>
        </tbody>
      </table>
    </div>
    <script src="http://libs.useso.com/js/jquery/1.11.0/jquery.min.js" type="text/javascript"></script>
    <script>window.jQuery || document.write('<script src="js/jquery-2.1.1.min.js"><\/script>')</script>
    <script src="js/bootstrap.min.js" type="text/javascript"></script>
    <script src="js/jquery.filer.min.js" type="text/javascript"></script>
    <script src="js/prettify.js" type="text/javascript"></script>
    <script src="js/scripts.js" type="text/javascript"></script>
    <script src="js/custom.js" type="text/javascript"></script>
</body>
</html>

up.java

package up;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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 org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class up
 */
@WebServlet("/up")
public class up extends HttpServlet {
    private static final long serialVersionUID = 1L;

    // 上传文件存储目录
    private static final String UPLOAD_DIRECTORY = "../upload";

    // 上传配置
    private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 200; // 200MB
    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 500; // 500MB

    /**
     * 上传数据及保存文件
     */
    protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
        // 检测是否为多媒体上传
        if (!ServletFileUpload.isMultipartContent(request)) {
            // 如果不是则停止
            PrintWriter writer = response.getWriter();
            writer.println("Error: 表单必须包含 enctype=multipart/form-data");
            writer.flush();
            return;
        }

        // 配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // 设置临时存储目录
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload upload = new ServletFileUpload(factory);

        // 设置最大文件上传值
        upload.setFileSizeMax(MAX_FILE_SIZE);

        // 设置最大请求值 (包含文件和表单数据)
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // 中文处理
        upload.setHeaderEncoding("UTF-8"); 

        // 构造临时路径来存储上传的文件
        // 这个路径相对当前应用的目录
        String uploadPath = request.getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY;

        // 如果目录不存在则创建
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        try {
            // 解析请求的内容提取文件数据
            @SuppressWarnings("/unchecked")
            List<FileItem> formItems = upload.parseRequest(request);

            if (formItems != null && formItems.size() > 0) {
                // 迭代表单数据
                for (FileItem item : formItems) {
                    // 处理不在表单中的字段
                    if (!item.isFormField()) {
                        String fileName = new File(item.getName()).getName();
                        String filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);
                        // 在控制台输出文件的上传路径
                        System.out.println(filePath);
                        // 保存文件到硬盘
                        item.write(storeFile);
                        request.setAttribute("message",
                            "文件上传成功!");
                    }
                }
            }
        } catch (Exception ex) {
            request.setAttribute("message",
                    "错误信息: " + ex.getMessage());
        }
        // 跳转到 message.jsp
        request.getServletContext().getRequestDispatcher("/message.jsp").forward(
                request, response);
    }
}

look.java

package look;

import java.io.File;
import java.util.ArrayList;

import org.apache.tomcat.util.collections.SynchronizedQueue;

public class look {
    public  ArrayList<String> look() throws Exception {
        ArrayList<String> all=new ArrayList<String>(); 
        File dir = new File("/data/wwwroot/pic.myelf.club/upload"); //要遍历的目录
        return all=visitAllDirsAndFiles(dir);
    }
    public static ArrayList<String> visitAllDirsAndFiles(File dir) {
        ArrayList<String> all=new ArrayList<String>();
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                visitAllDirsAndFiles(new File(dir, children[i]));
                all.add(""+children[i]);
            }
        }
        return all;
    }
}

delete.java

package delete;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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 org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class delete
 */
@WebServlet("/delete")
public class delete extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        // 文件存储路径
        String DIRECTORY = "/data/wwwroot/pic.myelf.club/upload/";
        DIRECTORY=DIRECTORY+new String((request.getParameter("filename")).getBytes("ISO-8859-1"),"UTF-8");
        try{
            File file = new File(DIRECTORY);
            if(file.delete()){
                request.setAttribute("message",file.getName() + " 文件已被删除!");
            }else{
                request.setAttribute("message",file.getName() + " 文件删除失败!");
            }
        }catch(Exception e){
            e.printStackTrace();
        }

        // 跳转到 message.jsp
        request.getServletContext().getRequestDispatcher("/message.jsp").forward(
                request, response);
    }
}

message.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="refresh" content="3;url=index.jsp">
<title>文件上传结果</title>
</head>
<body>
    <center>
        <h2>${message}</h2>
        <a href="index.jsp">3s后自动跳转>></a>
    </center>
</body>
</html>

运行展示

结语

待更新

本文严禁转载!

Last modification:May 29th, 2019 at 04:08 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment