文件的上传并不只是在品牌管理中有需求,以后的其它服务也可能需要,因此我们创建一个独立的微服务,专门处理各种上传。

1.搭建模块

(1)创建模块

(2)依赖

我们需要EurekaClient和web依赖:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>leyou</artifactId>
<groupId>lucky.leyou.parent</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion> <groupId>lucky.leyou.upload</groupId>
<artifactId>leyou-upload</artifactId> <dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<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> </project>

(3)编写配置

server:
port: 8082
spring:
application:
name: upload-service
servlet:
multipart:
max-file-size: 5MB # 限制文件上传的大小
# Eureka
eureka:
client:
service-url:
defaultZone: http://localhost:10086/eureka
instance:
lease-renewal-interval-in-seconds: 5 # 每隔5秒发送一次心跳
lease-expiration-duration-in-seconds: 10 # 10秒不发送就过期

(4)引导类

package lucky.leyou;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @SpringBootApplication
@EnableDiscoveryClient
public class LeyouUploadApplication { public static void main(String[] args) {
SpringApplication.run(LeyouUploadApplication.class, args);
}
}

(5)模块初步结构图

2.编写上传功能

(1)Controller

package lucky.leyou.upload.controller;

import lucky.leyou.upload.service.IUploadService;
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; @Controller
@RequestMapping(path = "/upload")
public class UploadController { @Autowired
IUploadService iUploadService; @PostMapping(path = "/image")
public ResponseEntity<String> uploadImage(@RequestParam("file")MultipartFile file){
String url=this.iUploadService.uploadImage(file);
//若url为空,则返回400,上传失败
if(StringUtils.isBlank(url)){
return ResponseEntity.badRequest().build();
} return ResponseEntity.status(HttpStatus.CREATED).body(url);
}
}

(2)service

接口

package lucky.leyou.upload.service;

import org.springframework.web.multipart.MultipartFile;

public interface IUploadService {

    String uploadImage(MultipartFile file);
}

实现类

package lucky.leyou.upload.service.impl;

import lucky.leyou.upload.service.IUploadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.List; public class UploadServiceImpl implements IUploadService {
private static final List<String> CONTENT_TYPES = Arrays.asList("image/jpeg", "image/gif"); private static final Logger LOGGER = LoggerFactory.getLogger(UploadServiceImpl.class);
@Override
public String uploadImage(MultipartFile file) {
String originalFilename = file.getOriginalFilename();
// 校验文件的类型
String contentType = file.getContentType(); //利用浏览器开发者模式下可见的content-type,判断文件类型
//Content-Type: application/x-www-form-urlencoded
if (!CONTENT_TYPES.contains(contentType)){
// 文件类型不合法,直接返回null
LOGGER.info("文件类型不合法:{}", originalFilename);
return null;
} try {
// 校验文件的内容
BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
if (bufferedImage == null){
LOGGER.info("文件内容不合法:{}", originalFilename);
return null;
} // 保存到服务器
file.transferTo(new File("C:\\Users\\image\\" + originalFilename)); // 生成url地址,返回
return "http://image.leyou.com/" + originalFilename;
} catch (IOException e) {
LOGGER.info("服务器内部错误:{}", originalFilename);
e.printStackTrace();
}
return null;
}
}

(3)使用Nginx代理,实现域名访问

进入Nginx的安装路径E:\toolsoftware\nginx-1.14.0\nginx-1.14.0\conf,修改

添加一个server,如下配置

server {
listen 80;
server_name image.leyou.com; proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; location / {
root C:\\Users\\image;
}
}

重新加载Nginx

(4)修改host解析

(5)效果图

(6)修改Nginx配置文件

server {
listen 80;
server_name api.leyou.com; proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # 上传路径的映射
location /api/upload {
proxy_pass http://127.0.0.1:8082;
proxy_connect_timeout 600;
proxy_read_timeout 600; rewrite "^/api/(.*)$" /$1 break;
} location / {
proxy_pass http://127.0.0.1:10010;
proxy_connect_timeout 600;
proxy_read_timeout 600;
}

(7)重启nginx,再次上传,发现跟上次的状态码已经不一样了,但是依然报错

不过庆幸的是,这个错误已经不是第一次见了,跨域问题。

package lucky.leyou.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter; /**
* 利用cors解决跨域问题
*/
@Configuration
public class LeyouCorsConfig {
@Bean
public CorsFilter corsFilter() {
//1.添加CORS配置信息
CorsConfiguration config = new CorsConfiguration();
//1) 允许的域,不要写*,否则cookie就无法使用了
config.addAllowedOrigin("http://manage.leyou.com");
//2) 是否发送Cookie信息
config.setAllowCredentials(true);
//3) 允许的请求方式
config.addAllowedMethod("*");
// 4)允许的头信息
config.addAllowedHeader("*"); //2.添加映射路径,我们拦截一切请求
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration("/**", config); //3.返回新的CorsFilter.
return new CorsFilter(configSource);
}
}

(8)最终效果

<1>若文件类型不符合

<2>若类型符合

020 文件(图片)上传功能---涉及switchhost和Nginx的使用的更多相关文章

  1. java模拟表单上传文件,java通过模拟post方式提交表单实现图片上传功能实例

    java模拟表单上传文件,java通过模拟post方式提交表单实现图片上传功能实例HttpClient 测试类,提供get post方法实例 package com.zdz.httpclient; i ...

  2. megapix-image插件 使用Canvas压缩图片上传 解决手机端图片上传功能的问题

    最近在弄微信端的公众号.订阅号的相关功能,发现原本网页上用的uploadify图片上传功能到手机端有的手机类型上就不能用了,比如iphone,至于为啥我想应该不用多说了吧(uploadify使用fla ...

  3. Ueditor图片上传功能的配置

    之前的项目中碰到过图片上传功能的配置问题,但是没有记录下来,今天有个朋友突然又问到了我这个问题,当时没想起来之前怎么解决的,后来看了Ueditor的官方文档才回想起来. 官网文档巨多,一般大家遇到问题 ...

  4. drupal中安装CKEditor文本编辑器,并配置图片上传功能 之 方法二

    drupal中安装CKEditor文本编辑器,并配置图片上传功能 之 方法一 中介绍了ckeditor的安装和配置方法,其实还有另一种新方法,不用IMCE模块. 不过需要ckfinder的JS库,可以 ...

  5. WebUploader文件图片上传插件的使用

    最近在项目中用到了百度的文件图片上传插件WebUploader.分享给大家 需要在http://fex.baidu.com/webuploader/download.html点击打开链接下载WebUp ...

  6. Retrofit 2.0 轻松实现多文件/图片上传/Json字符串/表单

    如果嫌麻烦直接可以用我封装好的库:Novate: https://github.com/Tamicer/Novate 通过对Retrofit2.0的前两篇的基础入门和案例实践,掌握了怎么样使用Retr ...

  7. summernote图片上传功能保存到服务器指定文件夹+php代码+java方法

    1.summernote富文本编辑器 summernote是一款基于bootstrap的富文本编辑器,是一款十分好用的文本编辑器,还附带有图片和文件上传功能. 那么在我们网站中想吧这个图片上传到服务器 ...

  8. Dede后台广告管理模块增加图片上传功能插件

    用户问题:网站广告后台管理非常方便,但是织梦后台的广告管理模块,发布广告时图片没有上传选项,只能用URL地址,很不方便,那么织梦帮就教大家一个方法实现广告图片后台直接上传,非常方便.先给大家看下修改后 ...

  9. 织梦DedeCMS广告管理模块增加图片上传功能插件

    网站广告后台管理非常方便,但是织梦后台的广告管理模块,发布广告时图片没有上传选项,只能用URL地址,很不方便,那么下面就教大家一个方法实现广告图片后台直接上传,非常方便. 先给大家看下修改后的广告图片 ...

随机推荐

  1. bash信号捕捉

    我们ping一个主机,然后按下ctrl+c那么就会终止这个ping动作,如下图: 可是如果使用一个循环来逐个ping不同主机,你再按下ctrl+c就会发现停不下来,直到循环完成,如下图: #!/bin ...

  2. vue 的 Class 与 Style 绑定

    操作元素的 class 列表和内联样式是数据绑定的一个常见需求.因为它们都是属性,所以我们可以用 v-bind 处理它们:只需要通过表达式计算出字符串结果即可.不过,字符串拼接麻烦且易错.因此,在将 ...

  3. maven 学习---Maven教程

    Apache Maven是一个软件项目管理和综合工具.基于项目对象模型(POM)的概念,Maven可以从一个中心资料片管理项目构建,报告和文件. 本教程将介绍如何使用Maven在Java开发,或任何其 ...

  4. flink dataset join笔记

    1.dataset的join连接,通过key进行关联,一般情况下的join都是inner join,类似sql里的inner join key包括以下几种情况: a key expression a ...

  5. Centos7配置ssh免密登录群发

    ssh免密登录是客户端发送自己的公钥到服务器.用公钥进行解密,自己生成的私钥进行加密. 首先在客户端查看sshd服务是否启动 [zhiwei@zhiwei1 ~]$ ps -Af|grep sshd; ...

  6. day 68 作业

    ''' 有以下成绩单数据 scores = [ { name: 'Bob', math: 97, chinese: 89, english: 67 }, { name: 'Tom', math: 67 ...

  7. Kibana 学习资料

    Kibana 学习资料 网址 Kibana 官方文档 https://s0www0elastic0co.icopy.site/guide/en/kibana/current/introduction. ...

  8. 重新学习Spring注解——AOP

    面向切面编程——思想:在一个地方定义通用功能,但是可以通过声明的方式定义这个功能要以何种方式在何处运用,而无须修改受影响的类. 切面:横切关注点可以被模块化为特殊的类. 优点: 1.每个关注点都集中在 ...

  9. jenkins中 Slave使用Docker

    原因就不说了,网上的自动化测试Docker教程太不靠谱,还是学学官网吧. 目的: 在现在各种虚拟化的大条件下,还在建立N个节点机器或节点机器搞N个并发,是不是太不方便了. 如果一个机器搞N个并发,在自 ...

  10. Http请求头中 X-Requested-With

    String requestedWith = ((HttpServletRequest) request).getHeader("X-Requested-With"); 如果 re ...