博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring+SpringMvc+Mybatis+多个文件上传与下载
阅读量:5154 次
发布时间:2019-06-13

本文共 7437 字,大约阅读时间需要 24 分钟。

关于ssm整合请看我的第一篇,这里只讲文件上传与下载

首先加入相关依赖:

commons-fileupload
commons-fileupload
1.3.3

在spring配置文件中加入文件配置:

整个项目目录如图:

在数据库中新建表,表结构如下:

 

Upfile.java:

 

package com.test.model;import org.springframework.stereotype.Component;@Componentpublic class UpFile {    private int id;    private String filename;    private String filepath;        public UpFile() {        super();    }    public UpFile(int id, String filename, String filepath) {        super();        this.id = id;        this.filename = filename;        this.filepath = filepath;    }    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getFilename() {        return filename;    }    public void setFilename(String filename) {        this.filename = filename;    }    public String getFilepath() {        return filepath;    }    public void setFilepath(String filepath) {        this.filepath = filepath;    }    @Override    public String toString() {        return "UpFile [id=" + id + ", filename=" + filename + ", filepath=" + filepath + "]";    }        }

UpFileMapper.java:

package com.test.mapper;import java.util.List;import com.test.model.UpFile;public interface UpFileMapper {    UpFile selectFileById(int id);    void InsertUpFile(UpFile upFile);    List
selectAllFile(); }

UpFileMapper.xml:

insert into upfile (filename,filepath) values (#{filename},#{filepath})

FileService.java:

package com.test.service;import java.util.List;import com.test.model.UpFile;public interface FileService {    UpFile selectFileById(int id);    void InsertUpFile(UpFile upFile);    List
selectAllFile();}

FileServiceImpl.java:

package com.test.service;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.test.mapper.UpFileMapper;import com.test.model.UpFile;@Servicepublic class FileServiceImpl implements FileService{    @Autowired    UpFileMapper upFileMapper;    @Override    public UpFile selectFileById(int id) {        // TODO Auto-generated method stub        return upFileMapper.selectFileById(id);    }    @Override    public void InsertUpFile(UpFile upFile) {        // TODO Auto-generated method stub        upFileMapper.InsertUpFile(upFile);    }    @Override    public List
selectAllFile() { // TODO Auto-generated method stub return upFileMapper.selectAllFile(); }}

FileController.java:

package com.test.controller;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.io.UnsupportedEncodingException;import java.net.URLEncoder;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.multipart.MultipartFile;import com.test.model.UpFile;import com.test.service.FileService;@RequestMapping("/file")@Controllerpublic class FileController {    @Autowired    FileService fileService;    @RequestMapping("/fileup")    //参数中的files要和页面中input输入框的name值相同    public String fileup(MultipartFile[] files, HttpServletRequest request) throws IllegalStateException, IOException {        //获取文件上传路径        String path = request.getSession().getServletContext().getRealPath("upload");        System.out.println(path);        StringBuffer stringBuffer=new StringBuffer();        for (MultipartFile multipartFile : files) {                if(!multipartFile.isEmpty()) {                //将多个文件名拼接在一个字符串中,用;分隔                stringBuffer.append(multipartFile.getOriginalFilename());                stringBuffer.append(";");                File dir=new File(path, multipartFile.getOriginalFilename());                if(!dir.exists()) {                    dir.mkdirs();                }                multipartFile.transferTo(dir);            }                    }        //去除最后一个;号        String s=stringBuffer.substring(0, stringBuffer.length()-1);        //存入数据库        fileService.InsertUpFile(new UpFile(0, s, path));        System.out.println(s);        //重定向至显示页面        return "redirect:/file/showallfiles";    }    @RequestMapping("/showallfiles")    public String showAllFile(Model model) {        //获取所有文件        List
allfiles=fileService.selectAllFile(); //新建map存储文件id和name,其中id作为键 HashMap
map=new HashMap<>(); for (UpFile upFile : allfiles) { //分割文件名字符串,将每个文件名添加到list中, List
filenamelist=new ArrayList<>(); String[] filenamearr=upFile.getFilename().split(";"); for (String string : filenamearr) { filenamelist.add(string); } //list作为map的值 map.put(upFile.getId()+"", filenamelist); } model.addAttribute("files", map); return "showfile"; } @ResponseBody @RequestMapping("/downfile") public String downfile(String filename,String id,HttpServletRequest request,HttpServletResponse response) throws IOException { System.out.println(filename+id); //根据id获取文件上传路径 UpFile upFile=fileService.selectFileById(Integer.parseInt(id)); String fileName = upFile.getFilepath()+"/"+filename; //防止中文乱码 filename = URLEncoder.encode(filename,"UTF-8"); System.out.println(filename); //获取输入流 InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName))); //设置文件下载头 response.addHeader("Content-Disposition", "attachment;fileName=" + filename); //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型 response.setContentType("multipart/form-data"); BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream()); int len = 0; while((len = bis.read()) != -1){ out.write(len); out.flush(); } out.close(); return "OK"; }}

 

在index.html中编写上传页面:

<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%>
Insert title here

在/WEB-INF/views/目录下新建showfile.html:

<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Insert title here
${file.key}

最后,开启tomcat,输入网址:http://localhost:8080/ssm/

上传两个文件:

点击文件名下载:

结束!

转载于:https://www.cnblogs.com/zivzhu/p/8350634.html

你可能感兴趣的文章
TCP/IP 邮件的原理
查看>>
w3m常用快捷键
查看>>
【Unity 3D】学习笔记四十一:关节
查看>>
原型设计工具
查看>>
windows下的C++ socket服务器(4)
查看>>
css3 2d转换3d转换以及动画的知识点汇总
查看>>
【Java】使用Eclipse进行远程调试,Linux下开启远程调试
查看>>
js对象属性方法
查看>>
对Vue为什么不支持IE8的解释之一
查看>>
Maven安装配置
查看>>
ORA-10635: Invalid segment or tablespace type
查看>>
计算机改名导致数据库链接的诡异问题
查看>>
Windows 8 操作系统 购买过程
查看>>
软件工程课程-个人编程作业
查看>>
Java8内存模型—永久代(PermGen)和元空间(Metaspace)(转)
查看>>
ObjectiveC基础教程(第2版)
查看>>
centos 引导盘
查看>>
Notes of Daily Scrum Meeting(12.8)
查看>>
Apriori算法
查看>>
onlevelwasloaded的调用时机
查看>>