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

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. Shell 编程 正则表达式

    本篇主要写一些shell脚本正则表达式的使用基础. 概述 正则表达式分为基础正则表达式(Regular Expression)与扩展正则表达式(Extended Regular Expression) ...

  2. Linux shell while循环语句

    for :明确循环次数 while :不确定循环换次数 while循环 (1) while CONDITION:do       statement       statement       < ...

  3. Nginx编译安装脚本

      Nginx是高性能的web服务器和反向代理服务器,在互联网公司中被广泛使用.以下是Nginx在centos7系统下的一键编译安装脚本,仅供参考,具体编译参数选项请结合实际生产环境需求进行选择,脚本 ...

  4. Centos7防火墙firewalled基本使用

    firewalld支持动态更新技术并加入了区域(zone)的概念.简单来说,区域就是firewalld预先准备了几套防火墙策略集合(策略模板),用户可以根据生产场景的不同而选择合适的策略集合,从而实现 ...

  5. sftp常用命令

    help 查看sftp支持哪些命令 ls  查看当前目录下文件 cd 指定目录 lcd 更改和/或打印本地工作目录 pwd 查看当前目录 lpwd 打印本地工作目录 get xxx.txt 下载xxx ...

  6. HDU 1372 Knight Moves 题解

    Knight Moves Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Tota ...

  7. Fiddler抓包设置

    介绍 Fiddler 在 PC 端和移动端,模拟器抓取数据包 Fiddler抓取PC端数据包: 这里 Fiddler 抓取网页客户端的数据包时,其原理就是在 客户端/浏览器 和 服务器端 之间,加上了 ...

  8. 性能测试基础---jmeter webservice接口测试

    ·webservice接口测试实现.·SOA:面向服务的体系架构,主要为了应对大型系统的异构需求.典型的实现方式:webservice·微服务:为了对SOA这样的重服务架构进行解耦而存在的.一个or几 ...

  9. CentOS7配置本地Yum源

    从CentOS7官网下载DVD中存在需要的大部分软件,所以在没有网络的情况下可以配置yum源为本地的DVD,下载速度快,软件稳定.1. 如果使用虚拟机,那么就在虚拟机中挂载DVD的iso文件.2. 使 ...

  10. python基础语法17 面向对象4 多态,抽象类,鸭子类型,绑定方法classmethod与staticmethod,isinstance与issubclass,反射

    多态 1.什么是多态? 多态指的是同一种类型的事物,不同的形态. 2.多态的目的: “多态” 也称之为 “多态性”,目的是为了 在不知道对象具体类型的情况下,统一对象调用方法的规范(比如:名字). 多 ...