SpringBoot 2.x (3):文件上传
文件上传有两个要点
一是如何高效地上传:使用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):文件上传的更多相关文章
- springboot实现简单的文件上传
承接上一篇,这里记录一下简单的springboot文件上传的方式 首先,springboot简单文件上传不需要添加额外的jar包和配置 这里贴一下后端controller层的实现代码 补一份前台的HT ...
- SpringBoot整合SpringMVC完成文件上传
1.编写Controller /** * SPringBoot文件上传 */ //@Controller @RestController //表示该类下的方法的返回值会自动做json格式的转换 pub ...
- springboot(九)文件上传
在企业级项目开发过程中,上传文件是最常用到的功能.SpringBoot集成了SpringMVC,当然上传文件的方式跟SpringMVC没有什么出入.下面我们来创建一个SpringBoot项目完成单个. ...
- Springboot 一行代码实现文件上传 20个平台!少写代码到极致
大家好,我是小富~ 技术交流,公众号:程序员小富 又是做好人好事的一天,有个小可爱私下问我有没有好用的springboot文件上传工具,这不巧了嘛,正好我私藏了一个好东西,顺便给小伙伴们也分享一下,d ...
- SpringBoot后台如何实现文件上传下载
1.单文件上传: @RequestMapping(value = "/upload") @ResponseBody public String upload(@RequestPar ...
- springboot整合OSS实现文件上传
OSS 阿里云对象存储服务(Object Storage Service,简称 OSS),是阿里云提供的海量.安全.低成本.高可靠的云存储服务.OSS可用于图片.音视频.日志等海量文件的存储.各种终端 ...
- springboot+thymeleaf 实现图片文件上传及回显
1. 创建一个springboot工程, 在此就不多说了(目录结构). 2. 写一个HTML页面 <!DOCTYPE html> <html lang="en" ...
- SpringBoot下文件上传与下载的实现
原文:http://blog.csdn.net/colton_null/article/details/76696674 SpringBoot后台如何实现文件上传下载? 最近做的一个项目涉及到文件上传 ...
- springboot 修改文件上传大小限制
springboot 1.5.9文件上传大小限制spring:http:multipart:maxFileSize:50MbmaxRequestSize:50Mb springboot 2.0文件上传 ...
- SpringBoot学习笔记(8)-----SpringBoot文件上传
直接上代码,上传文件的前端页面: <body> <form action="/index/upload" enctype="multipart/form ...
随机推荐
- 使用python转换markdown to html
起因 有很多编辑器可以直接将markdown转换成html,为什么还要自己写呢?因为我想写完markdown之后,即可以保存在笔记软件中(比如有道),又可以放到github进行版本管理,还可以发布到博 ...
- sparse-PCA(稀疏主成分分析)是什么?
不多说,直接上干货! 复杂降维技术有spare-PCA和sparse coding. 最近在科研需要,感谢下面的博主. Sparse PCA 稀疏主成分分析
- maven导入dom4j以及jaxen.jar报java.lang.UnsupportedOperationException:错误
<dependency> <groupId>jaxen</groupId> <artifactId>jaxen</artifactId> & ...
- 分页语句-取出sql表中第31到40的记录(以自动增长ID为主键)
sql server方案1: id from t order by id ) orde by id sql server方案2: id from t order by id) order by id ...
- Source code for redis.connection
redis.connection — redis-py 2.10.5 documentation http://redis-py.readthedocs.io/en/latest/_modules/r ...
- 解决手淘lib-flexible.js在移动端首次加载页面页面先放大后正常问题
例如这样 然后这样 出现这样的原因一般是 静态的,即html里有一些静态的(即非js动态添加的) 如果在页面加载完成后,页面是用js动态添加的,这个问题就不太明显, doc.addEventLis ...
- 搭建基于Maven的SSM框架
先展示文件结构图对工程结构有大致了解: 主要为 ssm-parent (用来管理jar包版本)是每个工程的父工程,ssm-common(用来处理底层数据),ssm-manager(对数据库信息进行操 ...
- leetcode 400 Add to List 400. Nth Digit
Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... Note:n is ...
- 自定义View分类与流程
自定义View分类与流程(进阶篇)## 转载出处: http://www.gcssloop.com/customview/CustomViewProcess/ 自定义View绘制流程函数调用链(简化版 ...
- (unix domain socket)使用udp发送>=128K的消息会报ENOBUFS的错误
一个困扰我两天的问题, Google和Baidu没有找到解决方法! 此文为记录这个问题,并给出原因和解决方法. 1.Unix domain socket简介 unix域协议并不是一个实际的协议族,而是 ...