spring boot 实现文件上传和下载,以及多文件上传

(1)、创建maven项目

(2)、在templates中创建html文件

html>
<html lang="en">
<head>
    <meta name="keywords" content="keyword1,keyword2,keyword3">meta>
    <meta name="description" content="this is my page">meta>
    <meta name="content-type" content="text/html; charset=UTF-8">meta>
    <title>fileUploadtitle>
head>
<body>

<form action="/upload" enctype="multipart/form-data" method="post">
    姓名:<input type="text" name="username"/>
    <br/>
    头像:<input type="file" name="filename"/>
          <input type="submit" value="上传"/>
form>
<hr/>
<a href="/download">文件下载a>
<br/>
<form action="/batch/upload" method="post" enctype="multipart/form-data">
    文件1:<input type="file" name="file"/><br/>
    文件2:<input type="file" name="file"/><br/>
    <input type="submit" value="多文件上传"/>
form>

body>
html>

(3)、在webapp下创建存储临时文件夹file

(4)、pom.xml代码:

xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0modelVersion>

   <groupId>com.example.filegroupId>
   <artifactId>fileuploadartifactId>
   <version>0.0.1-SNAPSHOTversion>
   <packaging>jarpackaging>

   <name>fileuploadname>
   <description>Demo project for Spring Bootdescription>

   <parent>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-starter-parentartifactId>
      <version>1.5.10.RELEASEversion>
      <relativePath/> 
   parent>

   <properties>
      <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
      <java.version>1.8java.version>
   properties>

   <dependencies>

      <dependency>
         <groupId>org.springframework.bootgroupId>
         <artifactId>spring-boot-starter-webartifactId>
      dependency>
      <dependency>
         <groupId>org.mybatis.spring.bootgroupId>
         <artifactId>mybatis-spring-boot-starterartifactId>
         <version>1.3.1version>
      dependency>

      <dependency>
         <groupId>org.springframework.bootgroupId>
         <artifactId>spring-boot-starter-testartifactId>
         <scope>testscope>
      dependency>

      <dependency>
         <groupId>commons-logginggroupId>
         <artifactId>commons-loggingartifactId>
         <version>1.2version>
      dependency>

      <dependency>
         <groupId>org.apache.maven.pluginsgroupId>
         <artifactId>maven-war-pluginartifactId>
         <version>3.2.0version>
      dependency>

      
      <dependency>
         <groupId>org.slf4jgroupId>
         <artifactId>slf4j-apiartifactId>
         <version>1.7.5version>
      dependency>

      <dependency>
         <groupId>org.slf4jgroupId>
         <artifactId>slf4j-log4j12artifactId>
         <version>1.7.12version>
      dependency>

      <dependency>
         <groupId>org.springframework.bootgroupId>
         <artifactId>spring-boot-starterartifactId>
         <exclusions>
            <exclusion>
               <groupId>org.springframework.bootgroupId>
               <artifactId>spring-boot-starter-loggingartifactId>
            exclusion>
         exclusions>
      dependency>

      <dependency>
         <groupId>org.springframework.bootgroupId>
         <artifactId>spring-boot-starter-log4jartifactId>
      dependency>

      
      <dependency>
         <groupId>org.springframework.bootgroupId>
         <artifactId>spring-boot-starter-thymeleafartifactId>
      dependency>
      <dependency>

         <groupId>org.springframework.bootgroupId>
         <artifactId>spring-boot-devtoolsartifactId>
         <optional>trueoptional>
      dependency>

      
      <dependency>
         <groupId>org.springframework.bootgroupId>
         <artifactId>spring-boot-starter-jdbcartifactId>
      dependency>

      <dependency>
         <groupId>mysqlgroupId>
         <artifactId>mysql-connector-javaartifactId>
         <scope>runtimescope>
      dependency>

      <dependency>
         <groupId>org.springframework.bootgroupId>
         <artifactId>spring-boot-starter-data-jpaartifactId>
      dependency>

      
      <dependency>
         <groupId>org.mybatis.spring.bootgroupId>
         <artifactId>mybatis-spring-boot-starterartifactId>
         <version>1.3.1version>
      dependency>

      <dependency>
         <groupId>com.alibabagroupId>
         <artifactId>druidartifactId>
         <version>1.0.26version>
      dependency>

      
      <dependency>
         <groupId>org.apache.tomcat.embedgroupId>
         <artifactId>tomcat-embed-jasperartifactId>
         <scope>providedscope>
      dependency>

      <dependency>
         <groupId>javax.servletgroupId>
         <artifactId>jstlartifactId>
         <version>1.2version>
      dependency>

   dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-maven-pluginartifactId>
         plugin>
      plugins>
   build>

project>

(5)、controller代码:

package com.example.file.fileupload.controller;

import com.example.file.fileupload.entity.Users;
import com.example.file.fileupload.service.UsersService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@Controller
public class FileController {
    //导入service层
    @Resource
    private UsersService usersService;

    @RequestMapping(value = "/goto",method = RequestMethod.GET)
    public String goUpload(){
        return "index";
    }
    //日志信息
    private static final Logger logger = LoggerFactory.getLogger(FileController.class);
    //文件上传相关代码
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    @ResponseBody
    public String upload(@RequestParam("filename") MultipartFile file,@RequestParam("username") String username,
                         HttpServletRequest request){
        //判断文件是否为空
        if(file.isEmpty()){
            return "文件为空";
        }
        //获取文件名
        String fileName = file.getOriginalFilename();
        logger.info("上传文件名为:"+fileName);
        //获取文件后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        logger.info("文件的后缀名为:"+suffixName);
        //上传后存放路径,webapp/file
        String filePath = request.getSession().getServletContext().getRealPath("file/");
        //重命名文件名
        String fileNewName = System.currentTimeMillis()+suffixName;
        //创建文件目录
        File src = new File(filePath+fileNewName);
        //检查文件目录是否存在
        if(!src.getParentFile().exists()){
            src.getParentFile().mkdirs();
        }
        //上传文件
        try{
            file.transferTo(src);
            //上传文件保存到数据库
            Users u = new Users();
            logger.info("username="+username);
            u.setUserName(username);
            u.setPhoto("file/"+fileNewName);
            this.usersService.insertUsers(u);
            return "上传成功!";
        }catch (Exception e){
            e.printStackTrace();
        }
        return "上传失败!";
    }

    //文件下载代码
    @RequestMapping(value = "/download",method = RequestMethod.GET)
    public String downFile(HttpServletRequest request, HttpServletResponse response){
        String fileName = "123.jpg";
        if(fileName != null){
            //获取当前路径下的文件
            String realPath = request.getServletContext().getRealPath("/file/")+fileName;
            File file = new File(realPath);
            //判断文件的对否存在
            if(file.exists()){
                //设置强制下载,不打开
                response.setContentType("application/x-msdownload");
                //设置文件名
                response.addHeader("Content-Disposition","attachment;fileName="+fileName);
                byte[]  bytes = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;

                try{
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int b = bis.read(bytes);
                    while(b != -1){
                        os.write(bytes,0,b);
                        b = bis.read(bytes);
                    }
                    os.close();
                    return "下载成功!";
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return "下载失败!";
    }

    //多文件上传
    @RequestMapping(value = "/batch/upload",method = RequestMethod.POST)
    @ResponseBody
    public String MoreFileUpload(HttpServletRequest request){
        //获取上传文件list
        List files = ((MultipartHttpServletRequest) request).getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream bos = null;
        //遍历文件
        for(int i = 0; i < files.size();i++){
            file = files.get(i);
            //判断文件的是否存在
            if(!file.isEmpty()){
                try{
                    //获取文件名
                    String fileName = file.getOriginalFilename();
                    logger.info("上传文件名为:"+fileName);
                    //获取文件后缀名
                    String suffixName = fileName.substring(fileName.lastIndexOf("."));
                    logger.info("文件的后缀名为:"+suffixName);
                    //上传后存放路径,webapp/file
                    String filePath = request.getSession().getServletContext().getRealPath("file/");
                    //重命名文件名
                    String fileNewName = System.currentTimeMillis()+suffixName;
                    //System.out.println("当前文件名:"+fileName);
                    //创建文件目录
                    File src = new File(filePath+fileNewName);
                    //检查文件目录是否存在
                    byte[] bytes = file.getBytes();
                    bos = new BufferedOutputStream(new FileOutputStream(src));
                    bos.write(bytes);
                    bos.close();
                }catch (Exception e){
                    bos = null;
                    return "上传失败原因是:"+e.getMessage();
                }
            }
            return "上传失败!";
        }
        return "上传成功!";
    }
}

(6)、运行http://localhost:8080/**即可

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