SpringBoot文件上传下载和多文件上传(图文详解)

SpringBoot文件上传下载和多文件上传(图文详解)最近在学习SpringBoot,以下是最近学习整理的实现文件上传下载的java代码:1、开发环境:IDEA15+Maven+JDK1.82、新建一个maven工程:3、工程框架4、pom.xml文件依赖项

大家好,又见面了,我是你们的朋友全栈君。

本人微信公众号:CPP进阶之旅
如果觉得这篇文章对您有帮助,欢迎关注 “CPP进阶之旅” 学习更多技术干货

最近在学习SpringBoot,以下是最近学习整理的实现文件上传下载的java代码:
1、开发环境:
IDEA15+ Maven+JDK1.8
2、新建一个maven工程:
这里写图片描述
3、工程框架
这里写图片描述
4、pom.xml文件依赖项

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>SpringWebContent</groupId>
  <artifactId>SpringWebContent</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>SpringWebContent Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.3.RELEASE</version>
  </parent>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-devtools</artifactId>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <properties>
    <java.version>1.8</java.version>
  </properties>
  <build>
    <finalName>SpringWebContent</finalName>
  <plugins>
  <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
  </plugin>
</plugins>
  </build>
</project>

5、Application.java

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

6、FileController.java

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@Controller
public class FileController {
    @RequestMapping("/greeting")
    public String greeting(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
        model.addAttribute("name", name);
        return "greeting";
    }
    private static final Logger logger = LoggerFactory.getLogger(FileController.class);
    //文件上传相关代码
    @RequestMapping(value = "upload")
    @ResponseBody
    public String upload(@RequestParam("test") MultipartFile file) {
        if (file.isEmpty()) {
            return "文件为空";
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        logger.info("上传的文件名为:" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        logger.info("上传的后缀名为:" + suffixName);
        // 文件上传后的路径
        String filePath = "E://test//";
        // 解决中文问题,liunx下中文路径,图片显示问题
        // fileName = UUID.randomUUID() + suffixName;
        File dest = new File(filePath + fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            return "上传成功";
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }

    //文件下载相关代码
    @RequestMapping("/download")
    public String downloadFile(org.apache.catalina.servlet4preview.http.HttpServletRequest request, HttpServletResponse response){
        String fileName = "FileUploadTests.java";
        if (fileName != null) {
            //当前是从该工程的WEB-INF//File//下获取文件(该目录可以在下面一行代码配置)然后下载到C:\\users\\downloads即本机的默认下载的目录
            String realPath = request.getServletContext().getRealPath(
                    "//WEB-INF//");
            File file = new File(realPath, fileName);
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition",
                        "attachment;fileName=" +  fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    System.out.println("success");
                } 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 null;
    }
    //多文件上传
    @RequestMapping(value = "/batch/upload", method = RequestMethod.POST)
    @ResponseBody
    public String handleFileUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request)
                .getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(
                            new File(file.getOriginalFilename())));
                    stream.write(bytes);
                    stream.close();

                } catch (Exception e) {
                    stream = null;
                    return "You failed to upload " + i + " => "
                            + e.getMessage();
                }
            } else {
                return "You failed to upload " + i
                        + " because the file was empty.";
            }
        }
        return "upload successful";
    }

7、index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>Get your greeting <a href="/greeting">here</a></p>
<form action="/upload" method="POST" enctype="multipart/form-data">
    文件:<input type="file" name="test"/>
    <input type="submit" />
</form>
<a href="/download">下载test</a>
<p>多文件上传</p>
<form method="POST" enctype="multipart/form-data" action="/batch/upload">
    <p>文件1:<input type="file" name="file" /></p>
    <p>文件2:<input type="file" name="file" /></p>
    <p><input type="submit" value="上传" /></p>
</form>
</html>

本文代码参考Spring官网:https://spring.io/guides/gs/serving-web-content/
完整工程地址:http://download.csdn.net/detail/coding13/9739116

欢迎关注我的个人微信公众号,查看专业的客户端/服务端开发知识、笔试面试题目、程序员职场经验与心得分享。
在这里插入图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/131160.html原文链接:https://javaforall.net

赞 (0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 各大公司Java后端开发面试题总结

    各大公司Java后端开发面试题总结ThreadLocal(线程变量副本)Synchronized实现内存共享,ThreadLocal为每个线程维护一个本地变量。采用空间换时间,它用于线程间的数据隔离,为每一个使用该变量的线程提供一个副本,每个线程都可以独立地改变自己的副本,而不会和其他线程的副本冲突。ThreadLocal类中维护一个Map,用于存储每一个线程的变量副本,Map中元素的键为线程对象,而值为对应线程的变量副本。Thre

    2022年5月6日
  • VMware 虚拟机里连不上网的五种解决方案「建议收藏」

    VMware 虚拟机里连不上网的五种解决方案「建议收藏」在VMware虚拟机里的虚拟机系统连接不上网络首先,注意查看适配器选项里的网络连接这两个网络连接是否存在,如果不存在可以重新装一下VM如果存在,连不上网解决办法一:虚拟机设置里,找到“网络适配器”,右边的网络连接选择“NAT模式”,如果不行的话再linux系统。还是不行的话接着看第二种解决方案。解决方法二:可能原因是VMwareNETService…

    2022年6月26日
  • 采用CreateThread()创建多线程程序[通俗易懂]

    采用CreateThread()创建多线程程序[通俗易懂]采用CreateThread()创建多线程程序在window环境下,Win32提供了一系列的API函数来完成线程的创建、挂起、恢复、终结以及通信等工作:1、主要的函数列表:序号函数名功能1CreateThread()创建一个新线程2ExitThread()正

    2022年7月11日
  • Fatal error: require(): Failed opening required ‘/www/wwwroot/xxxxxx/public/../thinkphp/start.php

    Fatal error: require(): Failed opening required ‘/www/wwwroot/xxxxxx/public/../thinkphp/start.php项目场景:在CentOS8中安装了宝塔,配置thinkphp5.1版本环境时出了问题,在此之前网站虚拟域名成功配置,能够访问站点创建成功的页面问题描述:在访问tp5默认页面时报错Warning:require():open_basedirrestrictionineffect.File(/home/wwwroot/xxxxxx/thinkphp/start.php)isnotwithintheallowedpath(s):(/home/wwwroot/xxxxxx/pub

    2022年8月22日
  • 你想要了解的黑客入门知识在这里

    你想要了解的黑客入门知识在这里开篇特此声明,萌新博主所写这篇文章的初衷并不是想让大家成为一名黑客,去做出一些违反国家法律规定的违规操作,只是单纯的想介绍一下成为黑客所要了解的知识以及一些必要的黑客术语,从读者的角度去满足一些计算机爱好者的好奇心。博主心底善良,为人正直,遵守国家法律规定。如有违反,望各位读者监督,另外图谋不轨者,严禁转载!!————————————————分割线———————————————————————…

    2022年5月5日
  • java是值传递还是引用传递 知乎_按值调用和按引用调用

    java是值传递还是引用传递 知乎_按值调用和按引用调用最近整理面试题,整理到值传递、引用传递,到网上搜了一圈,争议很大。带着一脸蒙圈,线上线下查了好多资料。最终有所收获,所以分享给大家,希望能对你有所帮助。首先说下我的感受,这个题目出的很好,但是在Java中这个题目是有问题的(在下面我会解释)。并且,有很多结论是Java中只有值传递。我认为这样说不够严谨。当然如果针对Java语言本身来讲,Java中只有值传递,没有…

    2022年10月23日

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号