文件上传有两个要点

一是如何高效地上传:使用MultipartFile替代FileOutputSteam

二是上传文件的路径问题的解决:使用路径映射

文件路径通常不在classpath,而是本地的一个固定路径或者是一个文件服务器路径

SpringBoot的路径:

src/main/java:存放代码

src/main/resources:存放资源

  static: 存放静态文件:css、js、image (访问方式 http://localhost:8080/js/main.js)

  templates:存放静态页面:html,jsp

  application.properties:配置文件

但是要注意:

比如我在static下新建index.html,那么就可以访问localhost:8080/index.html看到页面

如果在templates下新建index.html,那么访问会显示错误,除非在Controller中进行跳转

如果想对默认静态资源路径进行修改,则在application.properties中配置:

spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/ 

这里默认的顺序是先从/META-INF/resources中进行寻找,最后找到/public,可以在后边自行添加

文件上传不是老问题,这里就当是巩固学习了

方式:MultipartFile file,源自SpringMVC

首先需要一个文件上传的页面

在static目录下新建一个html页面:

<!DOCTYPE html>
<html>
<head>
<title>文件上传</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<form enctype="multipart/form-data" method="post" action="/upload">
文件:<input type="file" name="head_img" /> 姓名:<input type="text"
name="name" /> <input type="submit" value="上传" />
</form>
</body>
</html>

文件上传成功否需要返回的应该是一个封装的对象:

package org.dreamtech.springboot.domain;

import java.io.Serializable;

public class FileData implements Serializable {
private static final long serialVersionUID = 8573440386723294606L;
// 返回状态码:0失败、1成功
private int code;
// 返回数据
private Object data;
// 错误信息
private String errMsg; public int getCode() {
return code;
} public void setCode(int code) {
this.code = code;
} public Object getData() {
return data;
} public void setData(Object data) {
this.data = data;
} public String getErrMsg() {
return errMsg;
} public void setErrMsg(String errMsg) {
this.errMsg = errMsg;
} public FileData(int code, Object data) {
super();
this.code = code;
this.data = data;
} public FileData(int code, Object data, String errMsg) {
super();
this.code = code;
this.data = data;
this.errMsg = errMsg;
} }

处理文件上传的Controller:

package org.dreamtech.springboot.controller;

import java.io.File;
import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.dreamtech.springboot.domain.FileData;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; @RestController
public class FileController {
private static final String FILE_PATH = "D:\\temp\\images\\";
static {
File file = new File(FILE_PATH);
if (!file.exists()) {
file.mkdirs();
}
} @RequestMapping("/upload")
private FileData upload(@RequestParam("head_img") MultipartFile file, HttpServletRequest request) {
if (file.isEmpty()) {
return new FileData(0, null, "文件不能为空");
}
String name = request.getParameter("name");
System.out.println("用户名:" + name);
String fileName = file.getOriginalFilename();
System.out.println("文件名:" + fileName);
String suffixName = fileName.substring(fileName.lastIndexOf("."));
System.out.println("后缀名:" + suffixName);
fileName = UUID.randomUUID() + suffixName;
String path = FILE_PATH + fileName;
File dest = new File(path);
System.out.println("文件路径:" + path);
try {
// transferTo文件保存方法效率很高
file.transferTo(dest);
System.out.println("文件上传成功");
return new FileData(1, fileName);
} catch (Exception e) {
e.printStackTrace();
return new FileData(0, fileName, e.toString());
}
}
}

还有问题要处理,保存图片的路径不是项目路径,而是本地的一个固定路径,那么要如何通过URL访问到图片呢?

对路径进行映射:比如我图片保存在D:\temp\image,那么我们希望访问localhost:8080/image/xxx.png得到图片

可以修改Tomcat的配置文件,也可以按照下面的配置:

package org.dreamtech.springboot.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/image/**").addResourceLocations("file:D:/temp/images/");
}
}

还有一些细节问题不得忽略:对文件大小进行限制

package org.dreamtech.springboot.config;

import javax.servlet.MultipartConfigElement;

import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.unit.DataSize; @Configuration
public class FileSizeConfigurer {
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
// 单个文件最大10MB
factory.setMaxFileSize(DataSize.ofMegabytes(10L));
/// 设置总上传数据总大小10GB
factory.setMaxRequestSize(DataSize.ofGigabytes(10L));
return factory.createMultipartConfig();
}
}

打包后的项目如何处理文件上传呢?

顺便记录SpringBoot打包的坑,mvn clean package运行没有问题,但是不太方便

于是eclipse中run as maven install,但是会报错,根本原因是没有配置JDK,配置的是JRE:

解决:https://blog.csdn.net/lslk9898/article/details/73836745

图片量不大的时候,我们可以用自己的服务器自行处理,

如果图片量很多,可以采用图片服务器,自己用Nginx搭建或者阿里OSS等等

SpringBoot 2.x (3):文件上传的更多相关文章

  1. springboot实现简单的文件上传

    承接上一篇,这里记录一下简单的springboot文件上传的方式 首先,springboot简单文件上传不需要添加额外的jar包和配置 这里贴一下后端controller层的实现代码 补一份前台的HT ...

  2. SpringBoot整合SpringMVC完成文件上传

    1.编写Controller /** * SPringBoot文件上传 */ //@Controller @RestController //表示该类下的方法的返回值会自动做json格式的转换 pub ...

  3. springboot(九)文件上传

    在企业级项目开发过程中,上传文件是最常用到的功能.SpringBoot集成了SpringMVC,当然上传文件的方式跟SpringMVC没有什么出入.下面我们来创建一个SpringBoot项目完成单个. ...

  4. Springboot 一行代码实现文件上传 20个平台!少写代码到极致

    大家好,我是小富~ 技术交流,公众号:程序员小富 又是做好人好事的一天,有个小可爱私下问我有没有好用的springboot文件上传工具,这不巧了嘛,正好我私藏了一个好东西,顺便给小伙伴们也分享一下,d ...

  5. SpringBoot后台如何实现文件上传下载

    1.单文件上传: @RequestMapping(value = "/upload") @ResponseBody public String upload(@RequestPar ...

  6. springboot整合OSS实现文件上传

    OSS 阿里云对象存储服务(Object Storage Service,简称 OSS),是阿里云提供的海量.安全.低成本.高可靠的云存储服务.OSS可用于图片.音视频.日志等海量文件的存储.各种终端 ...

  7. springboot+thymeleaf 实现图片文件上传及回显

    1. 创建一个springboot工程, 在此就不多说了(目录结构). 2. 写一个HTML页面 <!DOCTYPE html> <html lang="en" ...

  8. SpringBoot下文件上传与下载的实现

    原文:http://blog.csdn.net/colton_null/article/details/76696674 SpringBoot后台如何实现文件上传下载? 最近做的一个项目涉及到文件上传 ...

  9. springboot 修改文件上传大小限制

    springboot 1.5.9文件上传大小限制spring:http:multipart:maxFileSize:50MbmaxRequestSize:50Mb springboot 2.0文件上传 ...

  10. SpringBoot学习笔记(8)-----SpringBoot文件上传

    直接上代码,上传文件的前端页面: <body> <form action="/index/upload" enctype="multipart/form ...

随机推荐

  1. 跟面试官讲Binder(零)

    面试的时候,面试官问你说,简单说一下Android的Binder机制,你会怎么回答? 我想,我会这么说. 在Android启动的时候,Zygote进程孵化出第一个子进程叫SystemServer,而在 ...

  2. Android之弹出多级菜单

    使用布局文件创建菜单:(多级菜单) 在res下创建目录menu(假设已经有啦就不用再创建了) 在该menu目录下创建XML文件这里我把文件名称命名为menu 在创建的menu.XML文件里 写入: & ...

  3. Vi/Vim查找替换使用方法【转】

    原文地址:http://wzgyantai.blogbus.com/logs/28117977.html vi/vim 中可以使用 :s 命令来替换字符串.该命令有很多种不同细节使用方法,可以实现复杂 ...

  4. 那条linq语句为啥这么慢

    目前所在的项目大量使用了linq,结果有个地方出现了严重的性能问题.一个统计需要3.40秒.头头焦头烂额之际,也让我看看. 我向来喜欢性能调优,自诩编码极为注重性能.曾几何时,也动不动就把性能挂在嘴边 ...

  5. 错误 1 无法将程序集“NBear.Data.dll”复制到文件“D:\newbpm\bpm\SureBpm\Bin\NBear.Data.dll”。无法将“D:\newbpm\bpm\SureSoft.WebServiceBaseLib\bin\Debug\NBear.Data.dll”添加到网站。 无法添加文件“Bin\NBear.Data.dll”。 拒绝访问。 D:\..

    错误 1 无法将程序集“NBear.Data.dll”复制到文件“D:\newbpm\bpm\SureBpm\Bin\NBear.Data.dll”.无法将“D:\newbpm\bpm\SureSof ...

  6. W5500EVB UDP模式的測试与理解

    之前的博文中已经介绍过W5500EVB 在TCP模式下的两种(Server及Client)传输数据的实现过程,那么传输控制协议中,UDP也是很经常使用的.这样的无连接的协议在很多其它场合为用户提供了便 ...

  7. JDBC连接数据库核心代码

    1.Oracle数据库   Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();   String url ...

  8. Linux内核--基于Netfilter的内核级包过滤防火墙实现

    测试内核版本:Linux Kernel 2.6.35----Linux Kernel 3.2.1 原创作品,转载请标明http://blog.csdn.net/yming0221/article/de ...

  9. 【转】Android性能优化之GPU过度绘制与图形渲染优化

    标签: android / 优化 / 过度绘制 / 图形渲染优化 Android之GPU过度绘制与图形渲染优化 写在前面的话 本文主要对过度绘制和图形渲染做一个概念性的描述,和简单的优化措施. 如果你 ...

  10. 【黑金教程笔记之006】【建模篇】【Lab 05 SOS信号之一】—笔记

    sos_module.v是产生SOS信号的功能模块.即有次序的输出莫斯码:点.画.间隔.control_module.v是一个定时触发器,每一段时间使能sos_module.v. 模块: /***** ...