SSM文件上传下载管理

1单文件管理

1_1单文件上传

https://www.cnblogs.com/zfding/p/8338429.html

项目结构

jar包

    <!--文件上下传-->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>

    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>

然后按照上面的结构图,在web底下创建一个文夹upload用来存储上传文件

然后在写一个FileUL类

package com.bdqn.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.InputStream;

/*
文件上传下载类
 */
@Controller
public class FileUL {
    /**
     * 单个文件上传
     * @param request
     * @return
     */
    @RequestMapping(value="/upload2",produces="text/html;charset=utf-8")
    @ResponseBody
    private String upload2(@RequestParam("file")CommonsMultipartFile partFile, HttpServletRequest request) {
        try {
            //读取文底下存储文件夹的路径
            String path = request.getServletContext().getRealPath("/upload");
            //读取前端的自定义文件名
            String name = request.getParameter("name");
            //读取上传文件的文件名
            String filename = partFile.getOriginalFilename();
            //拼接路径
            File file = new File(path+"/"+filename);
            //用IO流把文件写入到该文件夹下
            InputStream inputStream = partFile.getInputStream();
            FileUtils.copyInputStreamToFile(inputStream, file);

            if(inputStream!=null){
                inputStream.close();
            }
            return "文件上传成功!";
        } catch (Exception e) {
            e.printStackTrace();
            return "文件上传失败!";
        }
    }

    //无关紧要
    @RequestMapping("/index.html")
    public String index(){
        return "index";
    }

}

然后前端页面index.jsp(表单提交和AJAX提交)

<%--
  Created by IntelliJ IDEA.
  User: Admin
  Date: 2018/9/19
  Time: 10:47
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<script src="https://cdn.bootcss.com/jquery/1.8.1/jquery.min.js"></script>
<%--<table>--%>
    <%--<tr>--%>
        <%--<td>ID</td>--%>
        <%--<td>name</td>--%>
        <%--<td>price</td>--%>
    <%--</tr>--%>
    <%--<c:forEach items="${goods}" var="li" varStatus="str">--%>
        <%--<tr>--%>
            <%--<td>${li.id}</td>--%>
            <%--<td>${li.name}</td>--%>
            <%--<td>${li.price}</td>--%>
        <%--</tr>--%>
    <%--</c:forEach>--%>
<%--</table>--%>

<form  id ="form2" action="upload2" enctype="multipart/form-data" method="post">
    <input type = "file" name= 'file' />
    <input type="text" name="name" value="dzf"/>
    <input type="button" id = "button2" value="ajax上传" onclick="fileupload2()">
    <input type ="submit" value="直接上传">
</form>

<script>
    function fileupload2(){
        var formData = new FormData($("#form2")[0]);
        $.ajax({
            url:'upload2',
            type:'post',
            data:formData,
            //必须false才会自动加上正确的Content-Type
            contentType: false,
            //必须false才会避开jQuery对 formdata 的默认处理
            //XMLHttpRequest会对 formdata 进行正确的处理
            processData: false,
            success:function(data){
                alert(data);
            },
            error:function(data){
                alert(data);
                alert("后台发生异常");
            },
            cache:false,
            async:true
        });
    }
</script>
</body>
</html>

1_2单文件下载

    /*单文件下载*/
    /**
     * 文件下载
     * 单个文件下载
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("/down1")
    private void down(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String path = request.getServletContext().getRealPath("/upload");
        File file = new File(path);
        File[] files = file.listFiles();
        String name = files[0].getName();//随机获取一个文件,实际中按需编写代码
        System.out.println("文件的名字:"+name);
        response.addHeader("content-disposition", "attachment;filename="+name);
        FileUtils.copyFile(files[0], response.getOutputStream());
    }
<%--下载--%>
<form action="down1" name="form3" id = "form3" method="post">
     <input type = "submit" value="普通文件下载">
</form>

2多文件

1_1多文件上传

<%--
  Created by IntelliJ IDEA.
  User: Admin
  Date: 2018/9/19
  Time: 10:47
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<script src="https://cdn.bootcss.com/jquery/1.8.1/jquery.min.js"></script>
<%--<table>--%>
    <%--<tr>--%>
        <%--<td>ID</td>--%>
        <%--<td>name</td>--%>
        <%--<td>price</td>--%>
    <%--</tr>--%>
    <%--<c:forEach items="${goods}" var="li" varStatus="str">--%>
        <%--<tr>--%>
            <%--<td>${li.id}</td>--%>
            <%--<td>${li.name}</td>--%>
            <%--<td>${li.price}</td>--%>
        <%--</tr>--%>
    <%--</c:forEach>--%>
<%--</table>--%>

<%--单文件上传--%>
<form  id ="form2" action="upload2" enctype="multipart/form-data" method="post">
    <input type = "file" name= 'file' />
    <input type="text" name="name" value="dzf"/>
    <input type="button" id = "button2" value="ajax上传" onclick="fileupload2()">
    <input type ="submit" value="直接上传">
</form>

<%--单文件下载--%>
<form action="down1" name="form3" id = "form3" method="post">
     <input type = "submit" value="普通文件下载">
</form>

<%--多文件--%>
<form  id ="form5" action="upload3" enctype="multipart/form-data" method="post">
    <input type = "file" name= 'file' />
    <input type = "file" name= 'file' />
    <input type = "file" name= 'file' />
    <input type="text" name="name" value="dzf"/>
    <input type="button" id = "button3" value="多文件ajax上传" onclick="fileupload3()">
    <input type ="submit" value="多文件直接上传">
</form>

<%--多文件下载--%>
<form action="down2" name="form4" id = "form4" method="post">
    <input type = "submit" value="压缩文件下载">
</form>


<script>
    /*单文件*/
    function fileupload2(){
        var formData = new FormData($("#form2")[0]);
        $.ajax({
            url:'upload2',
            type:'post',
            data:formData,
            //必须false才会自动加上正确的Content-Type
            contentType: false,
            //必须false才会避开jQuery对 formdata 的默认处理
            //XMLHttpRequest会对 formdata 进行正确的处理
            processData: false,
            success:function(data){
                alert(data);
            },
            error:function(data){
                alert(data);
                alert("后台发生异常");
            },
            cache:false,
            async:true
        });
    }
    /*多文件*/
    function fileupload3(){
        var formData = new FormData($("#form5")[0]);
        $.ajax({
            url:'upload3',
            type:'post',
            data:formData,
            //必须false才会自动加上正确的Content-Type
            contentType: false,
            //必须false才会避开jQuery对 formdata 的默认处理
            //XMLHttpRequest会对 formdata 进行正确的处理
            processData: false,
            success:function(data){
                alert(data);
            },
            error:function(data){
                alert(data);
                alert("后台发生异常");
            },
            cache:false,
            async:true
        });
    }
</script>
</body>
</html>
package com.bdqn.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/*
文件上传下载类
 */
@Controller
public class FileUL {
    /**
     * 单个文件上传
     * @param request
     * @return
     */
    @RequestMapping(value="/upload2",produces="text/html;charset=utf-8")
    @ResponseBody
    private String upload2(@RequestParam("file")CommonsMultipartFile partFile, HttpServletRequest request) {
        try {
            //读取文底下存储文件夹的路径
            String path = request.getServletContext().getRealPath("/upload");
            //读取前端的自定义文件名
            String name = request.getParameter("name");
            //读取上传文件的文件名
            String filename = partFile.getOriginalFilename();
            //拼接路径
            File file = new File(path+"/"+filename);
            //用IO流把文件写入到该文件夹下
            InputStream inputStream = partFile.getInputStream();
            FileUtils.copyInputStreamToFile(inputStream, file);

            if(inputStream!=null){
                inputStream.close();
            }
            return "文件上传成功!";
        } catch (Exception e) {
            e.printStackTrace();
            return "文件上传失败!";
        }
    }

    /*单文件下载*/
    /**
     * 文件下载
     * 单个文件下载
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("/down1")
    private void down(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String path = request.getServletContext().getRealPath("/upload");
        File file = new File(path);
        File[] files = file.listFiles();
        String name = files[0].getName();//随机获取一个文件,实际中按需编写代码
        System.out.println("文件的名字:"+name);
        response.addHeader("content-disposition", "attachment;filename="+name);
        FileUtils.copyFile(files[0], response.getOutputStream());
    }


    /*多文件*/
    /**
     * 多个文件上载
     * @param request
     * @return
     */
    @RequestMapping(value="/upload3",produces="text/html;charset=utf-8")
    @ResponseBody
    private String upload3(@RequestParam("file")CommonsMultipartFile[] partFiles,HttpServletRequest request) {
        InputStream inputStream = null;
        try {
            String path = request.getServletContext().getRealPath("/upload");
            String name = request.getParameter("name");
            for (int i = 0; i < partFiles.length; i++) {
                String filename = partFiles[i].getOriginalFilename();
                File file = new File(path+"/"+filename);
                inputStream = partFiles[i].getInputStream();
                FileUtils.copyInputStreamToFile(inputStream, file);
            }
            if(inputStream!=null){
                inputStream.close();
            }
            return "文件上传成功!";
        } catch (Exception e) {
            e.printStackTrace();
            return "文件上传失败!";
        }
    }

    /*多文件下载*/
    /**
     * 文件下载,一下次下载多个文件
     * 思路:先将多个文件压缩到一个压缩包里去,然后传到前台
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("/down2")
    private void down2(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String path = request.getServletContext().getRealPath("/upload");
        File file = new File(path);
        File[] files = file.listFiles();
        File zipFile =new File("test.zip");
        if(!zipFile.exists()){
            zipFile.createNewFile();
        }
        String zipName = zipFile.getName();
        response.addHeader("Content-Disposition", "attachment;filename="+zipName);
        //定义输出类型
//        response.setContentType("application/zip");
        ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(zipFile));
        BufferedInputStream in  =null;
        for(int i = 0;i<files.length;i++){
            String name = files[i].getName();
            System.out.println("文件的名字:"+name);
            ZipEntry zipEntry = new ZipEntry(name);
            zip.putNextEntry(zipEntry);
            in = new BufferedInputStream(new FileInputStream(files[i]));
            int len = 0;
            byte [] btyes = new byte[1024*4];
            while((len=in.read(btyes))!=-1){
                zip.write(btyes, 0, len);
            }
        }
        zip.flush();
        zip.close();
        in.close();
        FileUtils.copyFile(zipFile, response.getOutputStream());
        if(zipFile.exists()){
            if(zipFile.delete()){
                System.out.println("压缩包删成功!!");
            }else{
                System.out.println("压缩包产出失败!!");
            }

        }
    }

    //无关紧要
    @RequestMapping("/index.html")
    public String index(){
        return "index";
    }

}

 

 

 

 

 

 

 

 

  • 2
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值