首页 > 其他分享 >使用SpringBoot实现文件的上传

使用SpringBoot实现文件的上传

时间:2023-11-23 10:01:28浏览次数:35  
标签:文件 outputStream SpringBoot inputStream import targetFile 上传

使用SpringBoot实现文件的上传

springboot可以直接使用 org.springframework.web.multipart.MultipartFile

所以非常容易实现

一、首先是简单的单文件上传

先在index.html页面下写一个简单的form表单

<h1>单文件</h1>
<form class="form-signin" th:action="@{/SingleFile/upload}" method="post" enctype="multipart/form-data">
<p><input type="file" name="myfile"/></p>
<p><input type="submit" value="上传"/></p>
<p style="color: red" th:text="${result_singlefile}" th:if="${not #strings.isEmpty(result_singlefile)}"></p>
</form>

注意使用thymeleaf

然后就到controller中写实现的代码

package com.manager.controller.FileController;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

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

@Controller
public class FileUploadController {

@PostMapping("/SingleFile/upload")
public String SingleFileUpLoad(@RequestParam("myfile") MultipartFile file, Model model) {
//判断文件是否为空
if(file.isEmpty()){
model.addAttribute("result_singlefile", "文件为空");
return "index";
}

//创建输入输出流
InputStream inputStream = null;
OutputStream outputStream = null;

try {
//指定上传的位置为 d:/upload/
String path = "d:/upload/";
//获取文件的输入流
inputStream = file.getInputStream();
//获取上传时的文件名
String fileName = file.getOriginalFilename();
//注意是路径+文件名
File targetFile = new File(path + fileName);
//如果之前的 String path = "d:/upload/" 没有在最后加 / ,那就要在 path 后面 + "/"

//判断文件父目录是否存在
if(!targetFile.getParentFile().exists()){
//不存在就创建一个
targetFile.getParentFile().mkdir();
}

//获取文件的输出流
outputStream = new FileOutputStream(targetFile);
//最后使用资源访问器FileCopyUtils的copy方法拷贝文件
FileCopyUtils.copy(inputStream, outputStream);
/*参数是通过源码
public static int copy(InputStream in, OutputStream out) throws IOException {
......
}
而得知的*/

//告诉页面上传成功了
model.addAttribute("result_singlefile", "上传成功");
} catch (IOException e) {
e.printStackTrace();
//出现异常,则告诉页面失败
model.addAttribute("result_singlefile", "上传失败");
} finally {
//无论成功与否,都有关闭输入输出流
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "index";
}

步骤已在注释中说明,现在运行项目测试

 

 

 

 选择文件 1.png

 

 

 

 点击上传

 

 

 

 成功!

 

二、多文件上传

与单文件类似,注意先遍历再执行

首先还是index.html

<h1>多文件</h1>
<form class="form-signin" th:action="@{/MultiFile/upload}" method="post" enctype="multipart/form-data">
<p><input type="file" name="myfile"/></p>
<p><input type="file" name="myfile"/></p>
<p><input type="file" name="myfile"/></p>
<p><input type="submit" value="上传"/></p>
<p style="color: red" th:text="${result_multifile}" th:if="${not #strings.isEmpty(result_multifile)}"></p>
</form>

 

再在刚才的controller中配置

 

@PostMapping("/MultiFile/upload")
public String MultiFileUpload(Model model, HttpServletRequest request) {

List<MultipartFile> list_files=((MultipartHttpServletRequest)request).getFiles("myfile");

if(list_files.isEmpty()){
model.addAttribute("result_multifile", "文件为空");
return "index";
}
InputStream inputStream = null;
OutputStream outputStream = null;
String path = "d:/upload/";
for (MultipartFile file : list_files) {
try {
inputStream = file.getInputStream();
String fileName = file.getOriginalFilename();
File targetFile = new File(path + fileName);

if(!targetFile.getParentFile().exists()){
targetFile.getParentFile().mkdir();
}

outputStream = new FileOutputStream(targetFile);
FileCopyUtils.copy(inputStream, outputStream);
model.addAttribute("result_multifile", "上传成功");
} catch (IOException e) {
e.printStackTrace();
model.addAttribute("result_multifile", "上传失败");
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return "index";
}

运行项目测试

 

 

 选择1.png  a.txt  b.txt

 

 

 

 

 成功!

 

 

 

以上就是简单的文件上传案例,因为只是简单的实现,所以没有将重复代码整合到utils下,比如关闭流的操作

 

参考文章:http://blog.ncmem.com/wordpress/2023/11/23/%e4%bd%bf%e7%94%a8springboot%e5%ae%9e%e7%8e%b0%e6%96%87%e4%bb%b6%e7%9a%84%e4%b8%8a%e4%bc%a0/

欢迎入群一起讨论

 

 

标签:文件,outputStream,SpringBoot,inputStream,import,targetFile,上传
From: https://www.cnblogs.com/songsu/p/17850909.html

相关文章

  • matlab的函数.m文件
    函数建立function [A]=name(参数1,参数2);‘’‘return;end保存为M文件,开头不要有多余的东西,不然就算在一个路径下,也无法识别函数名;也不是函数名和M文件名相同的问题,再说局部函数也不能同名。比如前面加个清理内存的东西clear;function [A]=name(参数1,参数2)...end这咋用都......
  • ext4文件系统故障修复
    ......
  • NS-3源码学习(三)Pcap文件分析
    NS-3源码学习(三)Pcap文件分析Pcap文件生成NS-3生成.pcap文件相关函数有EnablePcap()和EnalePcapAll(),支持第一个函数的类有ns3::YansWifiPhyHelperPointToPointEmuHelperCsmaHelper支持第二个函数的类有ns3::YansWifiPhyHelperPointToPointInternetStackHelper......
  • Linux文件管理
    在学习Linux文件管理章节时,我对Linux操作系统中的文件系统和目录结构有了更深入的了解。我学会了如何在终端中进行文件和目录的操作,包括创建、删除、复制、移动和重命名文件和目录。我也了解了不同类型的文件权限以及如何使用chmod和chown命令来管理文件和目录的权限。另......
  • windows 文件授权问题
    跨平台可执行权限介绍在类Unix系统(如Mac,Linux)中,执行权限是通过文件的权限位来控制的。而在Windows系统中,执行权限通常取决于文件扩展名和关联的执行程序,所以,当我们在跨平台的开发环境中,可能会遇到这样一个问题:在Windows系统上创建的脚本文件缺乏类Unix系统上的执行权......
  • 对linux下日志文件error监控
    对日志文件中的error进行监控,当日志文件中出现error关键字时,就截取日志(grep-ierror不区分大小写进行搜索"error"关键字,但是会将包含error大小写字符的单词搜索出来),大家可以去看这编文章   1)第一类日志在每天的日志目录下生产的error日志,此日志文件每天都会自动生成,里面有......
  • system.map文件中各符号含义
     如下图,红圈圈出来的符号含义是什么? 上述符号可以从该网站找到定义:Binutils-GNUProject-FreeSoftwareFoundation (像编译器的编译选项等也可以在该网站中找到说明) ......
  • springboot如何监控各种指标?
    以springboot2.7.17为例: 1:新增如下依赖:<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency> 然后,在你的配置文件(如 application.properties)中添加以下配......
  • cer文件如何查看 证书文件查看
    1.选择cer文件,点击安装 2.安装完成后,再次点击该文件,右键打开3.点击复制到文件,然后下一步4.选择base64编码,然后下一步 5.选择保存的文件名,点击下一步即可 6.然后用记事本打开该文件即可看到  翻译搜索复制......
  • U-BOOT分析之顶层Makefile文件
    U-BOOT分析(二)之顶层Makefile文件(1)U-BOOT版本u-boot版本:   u-boot-2021.01.tar.bz2Makefile&&make简介      Makefile:是一个描述文件定义一系列的规则来指定源文件编译的先后顺序,拥有特定的语法规则,makefile文件描述了整个工程中所有文件的__编译顺序,编译规......