文件上传有两个要点

一是如何高效地上传:使用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. 设计模式C++实现_2_简单工厂模式

    简单工厂模式 主要用于创建对象. 新加入类时. 不会影响曾经的系统代码. 核心思想是用一个工厂来依据输入的条件产生不同的类,然后依据不同类的 virtual 函数得到不同的结果. 以下以苹果手机的生产 ...

  2. java纯数字加密解密实例

    我们都知道,在用户加入信息时,一些比較敏感的信息,如身份证号,手机号,用户的登录password等信息,是不能直接明文存进数据库的.今天我们就以一个详细的样例来说明一下纯数字的java加密解密技术. ...

  3. 3 Angular 2 快速上手启动项目Demo

    Angular2.x与Angular1.x 的区别类似 Java 和 JavaScript 或者说是雷锋与雷峰塔的区别,想要运行Angular2需要安装一些第三方依赖,不会像Angular1.x那样, ...

  4. (八)unity4.6Ugui中文教程文档-------概要-UGUI Rich Text

    大家好,我是孙广东. 转载请注明出处:http://write.blog.csdn.net/postedit/38922399 更全的内容请看我的游戏蛮牛地址:mod=guide&view ...

  5. oracle的日期蛋

    一切都是扯鸡巴蛋. 在网上查oracle的日期函数用法,得到一大堆语法,林林总总,都是扯鸡巴蛋,没能解决我的问题. 其实,我想写这么一条语句:查找某个日期(不含时分秒)产生或有关的记录.咋写? SQL ...

  6. 2016/2/25 1, margin auto 垂直方向测试 无效 2,margin重叠 3,哪些是块状哪些是内联 4,display:block inline 导航栏把内联转块状最常见+ 扩展

    1.利用margin auto完成首页居中,并自行研究,竖直方向用margin auto,是什么效果#container{width:1002px;margin: 0px auto;}    竖直方向 ...

  7. Element is not clickable at point SeleniumWebdriverException

    Element is not clickable at point SeleniumWebdriverException | Selenium Easy http://www.seleniumeasy ...

  8. javaScript改变HTML

    改变HTML输出流: 在JavaScript中,document.write() 可用于直接向HTML输出流写内容 <!DOCTYPE html> <html> <bod ...

  9. Mac Launchpad图标调整

    Launchpad图标大小怎么调整?,很多人觉得默认Launchpad的应用程序图标很大,空间比较拥挤,看起来一点也不精致,那么我们怎样才能调整Launchpad的图标大小呢?其实可以通过调整Laun ...

  10. (续)linux SD卡初始化---mmc_sd_init_card函数

    mmc_sd_init_card剩下的关于UHS-I的分支结构. uhs-I的初始化流程图如图: 红线标出的部分是已经做了的事,与上一篇那个流程图是一致的,之后就是if分支中做的事. if分支中的函数 ...