SpringMVC之文件上传下载

SpringMVC之文件上传下载

  • 一、文件上传
  • 二、文件下载
  • 三、多文件上传

一、文件上传

配置多功能视图解析器(spring-mvc.xml):在Spring MVC的配置文件(spring-mvc.xml)中配置多功能视图解析器,以支持文件上传。

添加文件上传页面(upload.jsp):创建一个名为upload.jsp的JSP页面,用于用户上传文件。

做硬盘网络路径映射:配置服务器的硬盘路径映射到网络路径,确保上传的文件可以被访问和处理。

编写一个处理页面跳转的类:创建一个处理页面跳转的Java类,比如PageController.java或ClazzController.java,用于处理上传文件后的页面跳转逻辑。

package com.niyin.web;

import com.niyin.biz.tyBiz;
import com.niyin.model.ty;
import com.niyin.utils.PageBean;
import com.niyin.utils.PropertiesUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/clz")
public class tyController {
    @Autowired
    private tyBiz tyBiz;

    @RequestMapping("/list")
    public String list(ty t, HttpServletRequest request){
        PageBean pageBeanage=new PageBean();
        pageBeanage.setRequest(request);
        List<ty> books = tyBiz.selectByPager(t, pageBeanage);
        request.setAttribute("lst",books);
        request.setAttribute("pageBean",pageBeanage);
        return "list";
    };

    @RequestMapping("/add")
    public String add(ty t){
        int i = tyBiz.insertSelective(t);
        return "redirect:list";
    };

    @RequestMapping("/del")
    public String del(ty t){
        tyBiz.deleteByPrimaryKey(t.getTid());
        return "redirect:list";
    };
    @RequestMapping("/edit")
    public String edit(ty t){
        tyBiz.updateByPrimaryKeySelective(t);
        return "redirect:list";
    };

    @RequestMapping("/preSave")
    public String preSave(ty t, Model model) {
        if (t!=null&&t.getTid()!=null&&t.getTid()!=0){
            ty ts = tyBiz.selectByPrimaryKey(t.getTid());
            model.addAttribute("ts",ts);
        }
        return "edit";
    }
    @RequestMapping("/upload")
public  String upload(ty t,MultipartFile cfile){
        try {
        String dir= PropertiesUtil.getValue("dir");
        String server=PropertiesUtil.getValue("server");
    String Filename = cfile.getOriginalFilename();
    System.out.println("文件名"+Filename);
    System.out.println("文件类别"+cfile.getContentType());
            t.setTimage(server+Filename);
            tyBiz.updateByPrimaryKeySelective(t);
        FileUtils.copyInputStreamToFile(cfile.getInputStream(),new File(dir+Filename));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "redirect:list";
}
    @RequestMapping(value="/download")
    public ResponseEntity<byte[]> download(ty t,HttpServletRequest req){

        try {
            //先根据文件id查询对应图片信息 
            ty ts = this.tyBiz.selectByPrimaryKey(t.getTid());
            String diskPath = PropertiesUtil.getValue("dir");
            String reqPath = PropertiesUtil.getValue("server");
            String realPath = ts.getTimage().replace(reqPath,diskPath);
            String fileName = realPath.substring(realPath.lastIndexOf("/")+1);
            //下载关键代码
            File file=new File(realPath);
            HttpHeaders headers = new HttpHeaders();//http头信息
            String downloadFileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");//设置编码
            headers.setContentDispositionFormData("attachment", downloadFileName);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            //MediaType:互联网媒介类型  contentType:具体请求中的媒体类型信息
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    @RequestMapping("/uploads")
    public String uploads(HttpServletRequest req, ty t, MultipartFile[] files){
        try {
            StringBuffer sb = new StringBuffer();
            for (MultipartFile cfile : files) {
                //思路:
                //1) 将上传图片保存到服务器中的指定位置
                String dir = PropertiesUtil.getValue("dir");
                String server = PropertiesUtil.getValue("server");
                String filename = cfile.getOriginalFilename();
                FileUtils.copyInputStreamToFile(cfile.getInputStream(),new File(dir+filename));
                sb.append(filename).append(",");
            }
            System.out.println(sb.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:list";
    }

}
package com.niyin.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class PageController {
@RequestMapping("/page/{page}")
public String toPage(@PathVariable("page") String page){
    return page;
}
    @RequestMapping("/page/{dir}/{page}")
    public String toDirPage(@PathVariable("dir") String dir,@PathVariable("page") String page){
        return dir + "/"+ page;
    }

        @RequestMapping("/order/presave")
        public String orderpre() {
            return "/order/presave";

        }
    @RequestMapping("/clz/presave")
    public String clzerpre() {
        return "/clz/presave";

    }

}

初步模拟上传文件:实现一个初步的文件上传功能,可以将上传的文件保存到服务器指定的目录。
SpringMVC之文件上传下载_第1张图片

配置目录的配置文件:创建一个配置文件(比如resource.properties),用于配置上传文件保存的目录。

dir=D:/temp/upload/
server=/upload/

最终实现文件上传并显示:完成文件上传功能的开发,同时可以在页面上显示上传的文件列表或其他相关信息。
SpringMVC之文件上传下载_第2张图片

二、文件下载

方法代码:编写一个方法代码,用于处理文件下载请求。该方法根据请求参数或文件路径,读取相应的文件,并将文件内容写入HTTP响应流中,实现文件下载。

package com.niyin.web;

import com.niyin.biz.tyBiz;
import com.niyin.model.ty;
import com.niyin.utils.PageBean;
import com.niyin.utils.PropertiesUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/clz")
public class tyController {
    @Autowired
    private tyBiz tyBiz;

    @RequestMapping("/list")
    public String list(ty t, HttpServletRequest request){
        PageBean pageBeanage=new PageBean();
        pageBeanage.setRequest(request);
        List<ty> books = tyBiz.selectByPager(t, pageBeanage);
        request.setAttribute("lst",books);
        request.setAttribute("pageBean",pageBeanage);
        return "list";
    };

    @RequestMapping("/add")
    public String add(ty t){
        int i = tyBiz.insertSelective(t);
        return "redirect:list";
    };

    @RequestMapping("/del")
    public String del(ty t){
        tyBiz.deleteByPrimaryKey(t.getTid());
        return "redirect:list";
    };
    @RequestMapping("/edit")
    public String edit(ty t){
        tyBiz.updateByPrimaryKeySelective(t);
        return "redirect:list";
    };

    @RequestMapping("/preSave")
    public String preSave(ty t, Model model) {
        if (t!=null&&t.getTid()!=null&&t.getTid()!=0){
            ty ts = tyBiz.selectByPrimaryKey(t.getTid());
            model.addAttribute("ts",ts);
        }
        return "edit";
    }
    @RequestMapping("/upload")
public  String upload(ty t,MultipartFile cfile){
        try {
        String dir= PropertiesUtil.getValue("dir");
        String server=PropertiesUtil.getValue("server");
    String Filename = cfile.getOriginalFilename();
    System.out.println("文件名"+Filename);
    System.out.println("文件类别"+cfile.getContentType());
            t.setTimage(server+Filename);
            tyBiz.updateByPrimaryKeySelective(t);
        FileUtils.copyInputStreamToFile(cfile.getInputStream(),new File(dir+Filename));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "redirect:list";
}
    @RequestMapping(value="/download")
    public ResponseEntity<byte[]> download(ty t,HttpServletRequest req){

        try {
            //先根据文件id查询对应图片信息 
            ty ts = this.tyBiz.selectByPrimaryKey(t.getTid());
            String diskPath = PropertiesUtil.getValue("dir");
            String reqPath = PropertiesUtil.getValue("server");
            String realPath = ts.getTimage().replace(reqPath,diskPath);
            String fileName = realPath.substring(realPath.lastIndexOf("/")+1);
            //下载关键代码
            File file=new File(realPath);
            HttpHeaders headers = new HttpHeaders();//http头信息
            String downloadFileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");//设置编码
            headers.setContentDispositionFormData("attachment", downloadFileName);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            //MediaType:互联网媒介类型  contentType:具体请求中的媒体类型信息
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    @RequestMapping("/uploads")
    public String uploads(HttpServletRequest req, ty t, MultipartFile[] files){
        try {
            StringBuffer sb = new StringBuffer();
            for (MultipartFile cfile : files) {
                //思路:
                //1) 将上传图片保存到服务器中的指定位置
                String dir = PropertiesUtil.getValue("dir");
                String server = PropertiesUtil.getValue("server");
                String filename = cfile.getOriginalFilename();
                FileUtils.copyInputStreamToFile(cfile.getInputStream(),new File(dir+filename));
                sb.append(filename).append(",");
            }
            System.out.println(sb.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:list";
    }

}

JSP页面代码:创建一个JSP页面,用于触发文件下载请求。在该页面中,可以使用超链接或按钮等方式触发文件下载的方法。

<%--
  Created by IntelliJ IDEA.
  User: 林墨
  Date: 2023/9/9
  Time: 14:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>头像上传title>
head>
<body>
<form action="${ctx}/clz/upload" method="post" enctype="multipart/form-data">
    <label>班级编号:label><input type="text" name="tid" readonly="readonly" value="${param.tid}"/><br/>
    <label>班级图片:label><input type="file" name="cfile"/><br/>
    <input type="submit" value="上传图片"/>
form>


<form method="post" action="${ctx}/clz/uploads" enctype="multipart/form-data">
    <input type="file" name="files" multiple>
    <button type="submit">上传button>

form>
body>
html>

效果测试:运行应用程序,访问下载页面,并点击下载链接或按钮,验证文件下载功能是否正常工作。
SpringMVC之文件上传下载_第3张图片

三、多文件上传

jsp页面显示代码:修改上传页面(upload.jsp),支持同时上传多个文件。可以使用HTML的input标签设置multiple属性,以允许选择多个文件。

<%@ 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">
    <title>博客的编辑界面title>
head>
<body>
<form action="${pageContext.request.contextPath }/clz/${empty ts ? 'add' : 'edit'}" method="post">
    id:<input type="text" name="tid" value="${ts.tid }"><br>
    bname:<input type="text" name="tname" value="${ts.tname }"><br>
    price:<input type="text" name="tprice" value="${ts.tprice }"><br>
    price:<input type="text" name="tiamge" value="${ts.timage}"><br>
    <input type="submit">
form>
body>
html>

多文件上传方法:修改文件上传处理逻辑,使其能够处理同时上传的多个文件。可以使用循环遍历的方式,依次处理每个上传的文件。

package com.niyin.web;

import com.niyin.biz.tyBiz;
import com.niyin.model.ty;
import com.niyin.utils.PageBean;
import com.niyin.utils.PropertiesUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/clz")
public class tyController {
    @Autowired
    private tyBiz tyBiz;

    @RequestMapping("/list")
    public String list(ty t, HttpServletRequest request){
        PageBean pageBeanage=new PageBean();
        pageBeanage.setRequest(request);
        List<ty> books = tyBiz.selectByPager(t, pageBeanage);
        request.setAttribute("lst",books);
        request.setAttribute("pageBean",pageBeanage);
        return "list";
    };

    @RequestMapping("/add")
    public String add(ty t){
        int i = tyBiz.insertSelective(t);
        return "redirect:list";
    };

    @RequestMapping("/del")
    public String del(ty t){
        tyBiz.deleteByPrimaryKey(t.getTid());
        return "redirect:list";
    };
    @RequestMapping("/edit")
    public String edit(ty t){
        tyBiz.updateByPrimaryKeySelective(t);
        return "redirect:list";
    };

    @RequestMapping("/preSave")
    public String preSave(ty t, Model model) {
        if (t!=null&&t.getTid()!=null&&t.getTid()!=0){
            ty ts = tyBiz.selectByPrimaryKey(t.getTid());
            model.addAttribute("ts",ts);
        }
        return "edit";
    }
    @RequestMapping("/upload")
public  String upload(ty t,MultipartFile cfile){
        try {
        String dir= PropertiesUtil.getValue("dir");
        String server=PropertiesUtil.getValue("server");
    String Filename = cfile.getOriginalFilename();
    System.out.println("文件名"+Filename);
    System.out.println("文件类别"+cfile.getContentType());
            t.setTimage(server+Filename);
            tyBiz.updateByPrimaryKeySelective(t);
        FileUtils.copyInputStreamToFile(cfile.getInputStream(),new File(dir+Filename));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "redirect:list";
}
    @RequestMapping(value="/download")
    public ResponseEntity<byte[]> download(ty t,HttpServletRequest req){

        try {
            //先根据文件id查询对应图片信息 
            ty ts = this.tyBiz.selectByPrimaryKey(t.getTid());
            String diskPath = PropertiesUtil.getValue("dir");
            String reqPath = PropertiesUtil.getValue("server");
            String realPath = ts.getTimage().replace(reqPath,diskPath);
            String fileName = realPath.substring(realPath.lastIndexOf("/")+1);
            //下载关键代码
            File file=new File(realPath);
            HttpHeaders headers = new HttpHeaders();//http头信息
            String downloadFileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");//设置编码
            headers.setContentDispositionFormData("attachment", downloadFileName);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            //MediaType:互联网媒介类型  contentType:具体请求中的媒体类型信息
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    @RequestMapping("/uploads")
    public String uploads(HttpServletRequest req, ty t, MultipartFile[] files){
        try {
            StringBuffer sb = new StringBuffer();
            for (MultipartFile cfile : files) {
                //思路:
                //1) 将上传图片保存到服务器中的指定位置
                String dir = PropertiesUtil.getValue("dir");
                String server = PropertiesUtil.getValue("server");
                String filename = cfile.getOriginalFilename();
                FileUtils.copyInputStreamToFile(cfile.getInputStream(),new File(dir+filename));
                sb.append(filename).append(",");
            }
            System.out.println(sb.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:list";
    }

}

测试多文件上传:通过在上传页面选择多个文件并点击上传按钮,测试多文件上传功能是否正常工作。
SpringMVC之文件上传下载_第4张图片
SpringMVC之文件上传下载_第5张图片
可以看到已经成功了

你可能感兴趣的:(java,spring)