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

1.在leyou下新建Module:
在这里插入图片描述
2.打开pom.xml文件引入eurake客户端、web启动器、单元测试依赖:

 <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>

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.文件上传全部代码:

  • 文件目录:
    在这里插入图片描述
  • 控制层:
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<String> 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<String> 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);
    }
}

  • 将上传的图片放置在改路径:
    在这里插入图片描述
  • 修改hosts文件127.0.0.1映射地址增加一个image.leyou.com:
    在这里插入图片描述
  • 将请求/api/upload的代理到8082端口,且该配置必须在前面:
    在这里插入图片描述
  • 增加一个image.leyou.com的代理,将用来回显图片:
    在这里插入图片描述
  • 5.测试:
  • 成功上传图片:
    在这里插入图片描述
  • 成功回显图片:
    在这里插入图片描述
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值