乐优商城学习笔记07-文件上传以及跨域解决

1.在leyou下新建Module:
乐优商城学习笔记07-文件上传以及跨域解决_第1张图片
2.打开pom.xml文件引入eurake客户端、web启动器、单元测试依赖:

 
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-client
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-test
        
    

3.配置application.yml文件:

server:
  port: 8082
spring:
  application:
    name: upload-service
  servlet:
    multipart:
      max-file-size: 5MB   #配置上传最大文件大小
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:10086/eureka  #注册到eureka注册中心

  instance:
    lease-expiration-duration-in-seconds: 5  #心跳时间
    lease-renewal-interval-in-seconds: 15    #过期时间

4.文件上传全部代码:

  • 文件目录:
    乐优商城学习笔记07-文件上传以及跨域解决_第2张图片
  • 控制层:
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;

@Controller
@RequestMapping("upload")
public class UploadController {

    @Autowired
    private UploadService uploadService;

    @PostMapping("image")
    public ResponseEntity uploadImage(@RequestParam("file")MultipartFile file){
        String url = this.uploadService.uploadImage(file);
        if(StringUtils.isBlank(url)){
            return ResponseEntity.badRequest().build();
        }
        return ResponseEntity.status(HttpStatus.CREATED).body(url);

    }
}

  • service层:
package com.leyou.upload.service;

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.List;

@Service
public class UploadService {

    private static final List CONTENT_TYPES = Arrays.asList("image/gif","image/jpeg");

    private static final Logger LOGGER = LoggerFactory.getLogger(UploadService.class);

    public String uploadImage(MultipartFile file){

        //获取文件名称
        String originalFilename = file.getOriginalFilename();
        //校验文件类型
        String contentType = file.getContentType();
        if(!CONTENT_TYPES.contains(contentType)){
            LOGGER.info("文件类型不合法: {}",originalFilename);
            return null;
        }
        try {
            //校验文件内容
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if(bufferedImage == null){
                LOGGER.info("文件内容不合法:{}",originalFilename);
            }
            //保存到服务器
            file.transferTo(new File("G:\\SpringBoot_leyou\\image\\" + originalFilename));

            //返回url,进行回显
            return "http://image.leyou.com/" + originalFilename;
        } catch (IOException e) {
            LOGGER.info("服务器内部错误:" + originalFilename);
            e.printStackTrace();
        }
        return null;
    }
}

  • 新建包config,复制之前的LeyouCorsConfiguration.java解决跨域问题:
package com.leyou.upload.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;

@Configuration
public class LeyouCorsConfiguration {

    @Bean
    public CorsFilter corsFilter(){

        //初始化cors配置对象
        CorsConfiguration configuration = new CorsConfiguration();
        //允许跨域的域名,可以使用*来表示允许所有域名跨域访问
        configuration.addAllowedOrigin("http://manage.leyou.com");
        //是否允许携带cookie,如果允许则跨域域名不能使用*
        configuration.setAllowCredentials(true);
        configuration.addAllowedMethod("*");  //代表所有请求方法:get/post...
        configuration.addAllowedHeader("*");  //允许携带任何头信息


        //初始化cors配置源对象
        UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
        configurationSource.registerCorsConfiguration("/**",configuration);


        //返回corsFilter实例,参数:cors配置源对象
        return new CorsFilter(configurationSource);
    }
}

  • 将上传的图片放置在改路径:
    乐优商城学习笔记07-文件上传以及跨域解决_第3张图片
  • 修改hosts文件127.0.0.1映射地址增加一个image.leyou.com:
    乐优商城学习笔记07-文件上传以及跨域解决_第4张图片
  • 将请求/api/upload的代理到8082端口,且该配置必须在前面:
    乐优商城学习笔记07-文件上传以及跨域解决_第5张图片
  • 增加一个image.leyou.com的代理,将用来回显图片:
    乐优商城学习笔记07-文件上传以及跨域解决_第6张图片
  • 5.测试:
  • 成功上传图片:
    乐优商城学习笔记07-文件上传以及跨域解决_第7张图片
  • 成功回显图片:
    乐优商城学习笔记07-文件上传以及跨域解决_第8张图片

你可能感兴趣的:(乐优商城学习笔记,spring,java,mybatis,vue,spring,boot)