文件上传有两个要点

一是如何高效地上传:使用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. VUE组件如何与iframe通信问题

    vue组件内嵌一个iframe,现在想要在iframe内获取父vue组件内信息,由于本人技术有限,采用的是H5新特性PostMessage来解决跨域问题. postMessage内涵两个API: on ...

  2. Servlet的引入

    一.分析 此模式有问题: 1.jsp需要呼叫javabean StudentService stuService = new StudentServiceImpl(); List<Student ...

  3. Flex+Java+Blazeds

    1.环境:jdk1.6,Flex4.6 2.工具:MyEclipse10 3.server:Tomcat7 4.连接方式:Blazeds 5.项目类型:Flex项目 6.步骤 (1)新建Flex项目一 ...

  4. mysql命令行爱好者必备工具mycli

    mycli MyCLI is a command line interface for MySQL, MariaDB, and Percona with auto-completion and syn ...

  5. 设置ArcGIS的数据源

    我从别的地方拿到一份现成的地图文档(*.mxd),在该服务器上运行得好地地,图文并茂,但用我自己机器的arcMap打开就一片空白,啥都没有. 看左边的各个图层目录,图标上都有个粉红色的惊叹号,醒悟过来 ...

  6. 深入研究java.lang.Object类

    前言:Java的类库日益庞大.所包括的类和接口也不计其数.但当中有一些非常重要的类和接口,是Java类库中的核心部分.常见的有String.Object.Class.Collection.ClassL ...

  7. 在Orchard CMS Theme 用代码定义布局Widgets 配置

    在上篇中主要详细的叙述了代码的编写,这一篇主要讲解配置.可能有人会有疑问,在上一篇的代码里只有对数据的展示部分的编写,并没有提供数据源.这就是Orchard的强大之处,数据源是通过在后台配置的,那有人 ...

  8. go---weichart个人对Golang中并发理解

    个人觉得goroutine是Go并行设计的核心,goroutine是协程,但比线程占用更少.golang对并发的处理采用了协程的技术.golang的goroutine就是协程的实现. 十几个gorou ...

  9. bzoj 4711 小奇挖矿 —— 树形DP

    题目:https://www.lydsy.com/JudgeOnline/problem.php?id=4711 就是树形DP,然而也想了半天才把转移想清楚: f[x][j][0] 表示 x 去上面 ...

  10. String 对象

    1 你使用位置(索引)可以访问字符串中任何的字符: var str="this is a demo"; alert(str[3])//    s 字符串的索引从零开始, 所以字符串 ...