1. 引入pom.xml

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>

2. 编写application.yml

server:
port: 8082
spring:
application:
name: upload-service
servlet:
multipart:
max-file-size: 5MB

3. 编写UploadService

package com.leyou.upload.service;

import com.leyou.upload.controller.UploadController;
import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile; import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID; /**
* @author john
* @date 2019/11/30 - 15:20
*/
@Service
public class UploadService {
private static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class); //设置文件的contentType
private static final List<String> CONTENT_TYPES = Arrays.asList("image/jpg", "image/jpeg", "image/gif"); //设置文件存储的基路径
private static final String BASE_PATH = "D:\\imooc\\project\\images\\"; //设置文件返回的url
private static final String IMAGE_URL = "http://image.leyou.com/"; public String uploadImage(MultipartFile file) {
String originalFilename = file.getOriginalFilename();
String contentType = file.getContentType(); String ext = null;
if (originalFilename == null || !originalFilename.contains(".")) {
//图片名错误直接返回
return null;
} ext = originalFilename.substring(originalFilename.lastIndexOf(".")); // 1. 文件类型
if (contentType == null) {
LOGGER.info("文件{}获取不到contentType", originalFilename);
return null;
} if (!CONTENT_TYPES.contains(contentType.toLowerCase())) {
LOGGER.info("文件上传失败: {},文件类型{}不合法", originalFilename, contentType);
return null;
} try {
// 2. 校验文件的内容
BufferedImage bufferImage = ImageIO.read(file.getInputStream());
if (bufferImage == null || bufferImage.getWidth() <= 0 || bufferImage.getHeight() <= 0) {
LOGGER.info("文件上传失败: {},文件内容不合法", originalFilename);
return null;
} //设置文件上传后的生成的新名字
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
String newfileName = uuid + ext; //设置上传图片的实际存储目录
String dirPath = DateFormatUtils.format(new Date(), "yyyyMMdd");
String filepath = BASE_PATH + File.separator + dirPath; //创建新路径文件夹
File targetFile = new File(filepath);
if (!targetFile.exists()) {
targetFile.mkdirs();
} // 3. 保存到服务器
file.transferTo(new File(filepath + File.separator + newfileName));
// 4. 返回url路径 return IMAGE_URL + dirPath + File.separator + newfileName;
} catch (IOException e) {
e.printStackTrace();
LOGGER.info("文件{}上传失败:服务器异常 {}", originalFilename, e.getMessage());
return null;
}
}
}

3. 编写UploadController

package com.leyou.upload.controller;

import com.leyou.upload.service.UploadService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile; /**
* @author john
* @date 2019/11/30 - 15:18
*/
@Controller
@RequestMapping("upload")
public class UploadController {
@Autowired
private UploadService uploadService; @PostMapping("image")
public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file) {
String url = uploadService.uploadImage(file); if (StringUtils.isBlank(url)) {
return ResponseEntity.badRequest().build();
} return ResponseEntity.status(HttpStatus.CREATED).body(url);
}
}

测试上传

springboot处理单个文件上传的更多相关文章

  1. springboot文件上传: 单个文件上传 和 多个文件上传

    单个文件上传 //文件上传统一处理 @RequestMapping(value = "/upload",method=RequestMethod.POST) @ResponseBo ...

  2. SpringBoot: 6.文件上传(转)

    1.编写页面uploadFile.html <!DOCTYPE html> <html lang="en"> <head> <meta c ...

  3. Springboot如何启用文件上传功能

    网上的文章在写 "springboot文件上传" 时,都让你加上模版引擎,我只想说,我用不上,加模版引擎,你是觉得我脑子坏了,还是觉得我拿不动刀了. springboot如何启用文 ...

  4. spring mvc文件上传(单个文件上传|多个文件上传)

    单个文件上传spring mvc 实现文件上传需要引入两个必须的jar包    1.所需jar包:                commons-fileupload-1.3.1.jar       ...

  5. sruts2:单个文件上传,多个文件上传(属性驱动)

    文件上传功能在Struts2中得到了很好的封装,主要使用fileUpload上传组件. 1. 单个文件上传 1.1 创建上传单个文件的JSP页面.显示提交结果的JSP页面 uploadTest1.js ...

  6. Struts2 单个文件上传/多文件上传

    1导入struts2-blank.war所有jar包:\struts-2.3.4\apps\struts2-blank.war 单个文件上传 upload.jsp <s:form action= ...

  7. SpringBoot项目实现文件上传和邮件发送

    前言 本篇文章主要介绍的是SpringBoot项目实现文件上传和邮件发送的功能. SpringBoot 文件上传 说明:如果想直接获取工程那么可以直接跳到底部,通过链接下载工程代码. 开发准备 环境要 ...

  8. SpringBoot+BootStrap多文件上传到本地

    1.application.yml文件配置 # 文件大小 MB必须大写 # maxFileSize 是单个文件大小 # maxRequestSize是设置总上传的数据大小 spring: servle ...

  9. springboot升级导致文件上传自动配置/tmp目录问题解决

    1,..\web\src\main\resources\spring\web-men-applicationContext.xml 保留原有的bean配置 <bean id="mult ...

随机推荐

  1. C# Winform程序之间如何传递和接收参数 Process

    Program: static class Program    { /// <summary>         /// 应用程序的主入口点.         /// </summa ...

  2. POJ 3692 幼儿园做游戏 最大团 模板题

    Kindergarten Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 6191   Accepted: 3052 Desc ...

  3. [LOJ3119][CTS2019|CTSC2019]随机立方体:组合数学+二项式反演

    分析 感觉这道题的计数方法好厉害.. 一个直观的思路是,把题目转化为求至少有\(k\)个极大的数的概率. 考虑这样一个事实,如果钦定\((1,1,1),(2,2,2),...,(k,k,k)\)是那\ ...

  4. Android_(游戏)打飞机01:前言

    (游戏)打飞机01:前言 传送门 (游戏)打飞机02:游戏背景滚动 传送门 (游戏)打飞机03:控制玩家飞机 传送门 (游戏)打飞机04:绘画敌机.添加子弹   传送门 (游戏)打飞机05:处理子弹, ...

  5. Js基础知识(二) - 原型链与继承精彩的讲解

    作用域.原型链.继承与闭包详解 注意:本章讲的是在es6之前的原型链与继承.es6引入了类的概念,只是在写法上有所不同,原理是一样的. 几个面试常问的几个问题,你是否知道 instanceof的原理 ...

  6. 第七周学习总结&JAVA实验五报告。

    JAVA实验报告五: 实验四 类的继承 实验目的 理解抽象类与接口的使用: 了解包的作用,掌握包的设计方法. 实验要求 掌握使用抽象类的方法. 掌握使用系统接口的技术和创建自定义接口的方法. 了解 J ...

  7. kkfileview v2.0 发布,文件在线预览项目方案

    kkfileview文件在线预览 此项目为文件文档在线预览项目解决方案,项目使用流行的spring boot搭建,易上手和部署,部署好后可以独立提供预览服务,使用http接口访问,不需要和应用集成,具 ...

  8. Dark 数据类型

     dark基础数据类型  1数值型 num int a =1; double b=1.0; 2 字符型 string a ='hello'; 插值表达式${expression} int a = 1; ...

  9. Junit : how to add listener, and how to extends RunListener to override behaviors while failed

    http://junit.sourceforge.net/javadoc/org/junit/runner/notification/RunListener.html org.junit.runner ...

  10. golang 使用reflect反射结构体

    "反射结构体"是指在程序执行时,遍历结构体中的字段以及方法. 1.反射结构体 下面使用一个简单的例子说明如何反射结构体. 定义一个结构体,包括3个字段,以及一个方法. 通过refl ...