020 文件(图片)上传功能---涉及switchhost和Nginx的使用
文件的上传并不只是在品牌管理中有需求,以后的其它服务也可能需要,因此我们创建一个独立的微服务,专门处理各种上传。
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的使用的更多相关文章
- java模拟表单上传文件,java通过模拟post方式提交表单实现图片上传功能实例
		
java模拟表单上传文件,java通过模拟post方式提交表单实现图片上传功能实例HttpClient 测试类,提供get post方法实例 package com.zdz.httpclient; i ...
 - megapix-image插件 使用Canvas压缩图片上传 解决手机端图片上传功能的问题
		
最近在弄微信端的公众号.订阅号的相关功能,发现原本网页上用的uploadify图片上传功能到手机端有的手机类型上就不能用了,比如iphone,至于为啥我想应该不用多说了吧(uploadify使用fla ...
 - Ueditor图片上传功能的配置
		
之前的项目中碰到过图片上传功能的配置问题,但是没有记录下来,今天有个朋友突然又问到了我这个问题,当时没想起来之前怎么解决的,后来看了Ueditor的官方文档才回想起来. 官网文档巨多,一般大家遇到问题 ...
 - drupal中安装CKEditor文本编辑器,并配置图片上传功能 之 方法二
		
drupal中安装CKEditor文本编辑器,并配置图片上传功能 之 方法一 中介绍了ckeditor的安装和配置方法,其实还有另一种新方法,不用IMCE模块. 不过需要ckfinder的JS库,可以 ...
 - WebUploader文件图片上传插件的使用
		
最近在项目中用到了百度的文件图片上传插件WebUploader.分享给大家 需要在http://fex.baidu.com/webuploader/download.html点击打开链接下载WebUp ...
 - Retrofit 2.0 轻松实现多文件/图片上传/Json字符串/表单
		
如果嫌麻烦直接可以用我封装好的库:Novate: https://github.com/Tamicer/Novate 通过对Retrofit2.0的前两篇的基础入门和案例实践,掌握了怎么样使用Retr ...
 - summernote图片上传功能保存到服务器指定文件夹+php代码+java方法
		
1.summernote富文本编辑器 summernote是一款基于bootstrap的富文本编辑器,是一款十分好用的文本编辑器,还附带有图片和文件上传功能. 那么在我们网站中想吧这个图片上传到服务器 ...
 - Dede后台广告管理模块增加图片上传功能插件
		
用户问题:网站广告后台管理非常方便,但是织梦后台的广告管理模块,发布广告时图片没有上传选项,只能用URL地址,很不方便,那么织梦帮就教大家一个方法实现广告图片后台直接上传,非常方便.先给大家看下修改后 ...
 - 织梦DedeCMS广告管理模块增加图片上传功能插件
		
网站广告后台管理非常方便,但是织梦后台的广告管理模块,发布广告时图片没有上传选项,只能用URL地址,很不方便,那么下面就教大家一个方法实现广告图片后台直接上传,非常方便. 先给大家看下修改后的广告图片 ...
 
随机推荐
- 如何让SQL语句不执行默认排序,而是按照in语句的顺序返回结果
			
Oracle: ')order by instr('111,222,333,444,555,666',order_id); Mysql: ') order by instr(',111,222,333 ...
 - 关于VS C++中项目属性的一些名称的含义
			
这个属性页(Alt + F7)界面下的$开头的内容的含义 $(Platform), X64或X86类似的. $(SolutionDir),.sln的位置 $(Configuration), Debug ...
 - javascript中的12种循环遍历方法1
			
1:for循环 let arr = [1,2,3]; for(let i =0;i<arr.length;i++){ console.log(i,arr[i]) } //for循环是js中最常用 ...
 - <Android Studio> 2.APP开机启动
			
开机启动,也就是App随着机器开机而启动,在很多工业场景中是非常常见的. 开机启动的基本原理就是监听系统启动相关的广播,然后启动App. 为了实现开机启动,我人为的分为几个步骤 1.创建broadca ...
 - httpclient解析
			
1.HttpClient简介 HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性,它不仅使客户端发送Http请求变得容易,而且也方便开发人员测试接口(基于Http ...
 - 一个APACHE TOMCAT漏洞修复
			
这种情况加个SSL证书就行了 就是HTTPS协议
 - 安装docker后,导致qemu的桥接网络出现问题
			
按照Qemu-4.1 桥接网络设置中介绍的方法建立起桥接网络后,可以实现虚拟机和host的相互ping,但是在虚拟机里去ping其他跟host处于同一个网段的ip地址时却失败了,然后ifconfig后 ...
 - python处理excel函数xlrd、xlwt
			
https://www.jianshu.com/p/f2c9dff344c6 https://www.cnblogs.com/ilovepython/p/11068841.html 行列操作:http ...
 - Nginx Rewrite相关功能-rewrite指令
			
Nginx Rewrite相关功能-rewrite指令 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任.
 - 【Servlet】Servlet的配置
			
创建时间:6.15 Servlet的配置 1. 基本配置 其中url-pattern的配置方式: 1)完全匹配 访问的资源与配置的资源完全相同才能访问到 2)目录匹配 格式:/虚拟的目录../* ...