上机考试系统 commons-fileupload 上传与下载 && 压缩为 zip 文件 && 删除文件夹下所有内容

在 maven 中使用了 commons-fileupload,使用方法:

(一)上传

1.0 pom 文件依赖

<dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.2</version>
</dependency>

 

1-1.前端界面

<form action="" enctype="multipart/form-data" class="modifyall"
            method="post" id="uploadForm">
            <input type="file" name="file" id="file"
                style="display: inline-block" class="po"> 
       <input type="submit" class="layui-btn layui-btn-sm " value="上传" id="fileUpload">
</form>

1-2.js

function fileUpload() {
    var URL = root + "/teacher/teacherUpload";
    var data = new FormData($('#uploadForm')[0]);
    $.ajax({
        url : URL,
        type : "post",
        data : data,
        async : false,
        cache : false,
        processData : false,
        contentType : false,
        success : function(data) {
      //返回数据类型为 String
if (data == "ok") { location.reload(); } if (data == "min") {
      //如果文件大小小于最小上传值,返回 "min",并将最小值的大小存储在 session 中,通过<input type="hidden"> 和 id 获取最小值
var min = $("#min").val(); alert("文件必须大于" + min); location.reload(); } if (data == "max") {
      //同最小值 alert(
"文件必须小于" + max); location.reload(); } }, error : function(data) { alert("操作失败"); } }); }

1-3.Controller@ResponseBody    @RequestMapping("/teacherUpload")

public String upload(MultipartFile file, HttpServletRequest request, HttpServletRequest reponse)
            throws IOException {
        PageData pd = this.getPageData();

        // 根据考试 id 获取考试信息
        String testid = pd.getString("testid");
        List<PageData> list = this.teacherFacade.selectTestById(testid);
        List<PageData> system = this.teacherFacade.selectSystem();
        /*
         * 文件大小检测
         */
        long filesize = file.getSize();
        long minSize = (long) system.get(0).get("file_minsize");
        long maxSize = (long) system.get(0).get("file_maxsize");
// 文件小于最小值或大于最大值; if (minSize > filesize) { session.setAttribute("min", minSize + "Byte"); return "min"; } if (maxSize < filesize) { session.setAttribute("max", maxSize + "Byte"); return "max"; } // 保存路径为考试名 String path = request.getSession().getServletContext() .getRealPath("/ExamSystem/" + list.get(0).getString("testname")); System.out.println("path>>" + path); String fileName = file.getOriginalFilename(); // 将文件名加入到数据库 pd.put("submit", fileName); this.teacherFacade.updateaddfile(pd); System.out.println("fileName>>" + fileName); File dir = new File(path, fileName); System.out.println("dir.exists()>>" + dir.exists()); if (!dir.exists()) { dir.mkdirs(); } System.out.println("dir.exists()>>" + dir.exists()); // MultipartFile自带的解析方法 file.transferTo(dir); return "ok"; }

(二)下载

2-1 前端

<form action="downTest" name="form3" id="form3" method="post"><!-- action 是请求映射的地址 -->
    <input type="submit" class="test_down" value="下载查看" />
</form>

2-2 Controller

@ResponseBody
    @RequestMapping("/downTest")
    private void down(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // 根据考试 id 获取考试信息
        // list = this.studentFacade.selectTestById(testid);
        ServletContext application = request.getSession().getServletContext();
        List<PageData> list = (List<PageData>) application.getAttribute("RunTest");
        System.out.println(list);
        if (list != null) {
            String path = request.getServletContext().getRealPath("/") + "ExamSystem/"
                    + list.get(0).getString("testname") + "/";
            System.out.println(path);
            String fileName = list.get(0).getString("submit");
            fileName = new String(fileName.getBytes(), "ISO8859-1");//解决无法下载中文的问题
            //System.out.println(path + fileName);
            File file = new File(path + fileName);
            //System.out.println(file);
            if (file != null) {
                //System.out.println("文件的名字:" + fileName);
                response.addHeader("content-disposition", "attachment;filename=" + fileName);
                FileUtils.copyFile(file, response.getOutputStream());
            }

        }
    }

下载是会有中文名无法显示的问题,代码中加入 

fileName = new String(fileName.getBytes(), "ISO8859-1");

(三)打包为 zip 下载 (原文地址没找到...)

3-1 前端 

<a  id="downloadInfo" href="downZip?testid=${test.get('testid')}"
title="打包下载">打包下载</a>

3-2 Controller

@ResponseBody
    @RequestMapping("/downZip")
    public void downZip(HttpServletRequest request, HttpServletRequest reponse) throws IOException {

        PageData pd = this.getPageData();
        //response.setContentType("application/x-msdownload;");
        // System.out.println(pd);
        String testid = pd.getString("testid");
        System.out.println(testid);
        List<PageData> list = new ArrayList<PageData>();
        if (this.teacherFacade.selectTestById(testid) != null) {
            // 归档考试
            pd.put("test_signal", "3");
            this.teacherFacade.updateSignal(pd);
            list = this.teacherFacade.selectTestById(testid);
        }

        if (list != null) {

            try {

                String testName = list.get(0).getString("testname");
                String sourcePath = request.getServletContext().getRealPath("/") + "ExamSystem/" + testName;
                System.out.println(sourcePath);
                String zipName = testName + ".zip";
                zipName = new String(zipName.getBytes(), "ISO8859-1");
                System.out.println(zipName);
                String zipPath = request.getServletContext().getRealPath("/") + "ExamSystem/" + zipName;
                File file = new File(sourcePath);// 要被压缩的文件夹
                File zipFile = new File(zipPath);
                ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
                if (file.isDirectory()) {
                    File[] files = file.listFiles();
                    for (File fileSec : files) {
                        ZipUtil.recursionZip(zipOut, fileSec, "");
                    }
                }
                zipOut.close();

                if (zipFile != null) {
                    System.out.println("文件的名字:" + zipName);
                    response.addHeader("content-disposition", "attachment;filename=" + zipName);
                    FileUtils.copyFile(zipFile, response.getOutputStream());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

3-3 工具类

package com.ssm.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtil {

    /*
     * 文件压缩
     */
    public static void recursionZip(ZipOutputStream zipOut, File file, String baseDir) throws Exception {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File fileSec : files) {
                recursionZip(zipOut, fileSec, baseDir + file.getName() + File.separator);
            }
        } else {
            byte[] buf = new byte[1024];
            InputStream input = new FileInputStream(file);
            zipOut.putNextEntry(new ZipEntry(baseDir + file.getName()));
            int len;
            while ((len = input.read(buf)) != -1) {
                zipOut.write(buf, 0, len);
            }
            input.close();
        }
    }
}

 

(四)删除文件夹下的所有内容  原文地址

4-1 获取文件地址

String sourcePath = request.getSession().getServletContext().getRealPath("/") + "ExamSystem/"
                        + testName;

 

4-2 删除文件夹下所有内容

File sourceFile = new File(sourcePath);
if (sourceFile.exists()) {                                        
    DeleteFolderUtil.deleteFile(sourceFile);
}

4-3 工具类

package com.ssm.util;

import java.io.File;

public class DeleteFolderUtil {
    /*
     * 删除文件夹下所有内容
     */
    public static void deleteFile(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                deleteFile(files[i]);
            }
        }
        file.delete();
    }

}

 

 

 

 

 



posted @ 2018-11-29 16:25  宁任翃  阅读(461)  评论(0编辑  收藏  举报