首页 > Web开发 > 详细

leyou_05_文件上传

时间:2019-09-23 22:32:09      阅读:103      评论:0      收藏:0      [点我收藏+]

1.搭建一个新的微服务Ly-upload用来上传文件

2.导入文件上传到额依赖

<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>
    //Ly-common包含了自定义异常处理
<dependency> <groupId>com.leyou.common</groupId> <artifactId>Ly-common</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies>

 

 3.编写application.yaml的文件配置

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

 

 

4.起动类

@SpringBootApplication
@EnableDiscoveryClient
public class LyUploadApplication {
    public static void main(String[] args) {
        SpringApplication.run(LyUploadApplication.class);
    }
}

 

 

5.接受参数name="file"

当文件上传成功时返回一个文件路径   ResponseEntity.status(HttpStatus.OK).body(url);

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

    @Autowired
    private UploadService uploadService;
    @PostMapping("image") //当文件上传的时候 SpringMvc会自动把上传的文件封装到MultipartFile中去
    public ResponseEntity<String> uploadImg(@RequestParam("file") MultipartFile file) {

        String url=uploadService.uuploadImg(file);
     //
return ResponseEntity.status(HttpStatus.OK).body(url); } }

 

当文件上传的时候 SpringMvc会自动把上传的文件封装到MultipartFile中去。使用MultipartFile来接受文件
@RequestParam("file") MultipartFile file

6.文件上传

@Service
@Slf4j
public class UploadService {

    private static  final List<String> ALLOW_TYPES= Arrays.asList("image/jpeg","image/png");
    public String uploadImg(MultipartFile file) {
        try {

            //检验文件的类型 防止恶意文件
            String contentType = file.getContentType();
            if (!ALLOW_TYPES.contains(contentType)){
                throw  new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            };
            //校验文件的内容
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image==null){
                throw  new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }
            //保存文件到本地
            File local = new File("F:\\javaee\\IdeaResource\\uploadImg\\",file.getOriginalFilename());
            file.transferTo(local);
            //返回文件地址
            return "http://image.leyou.com/"+file.getOriginalFilename();
        } catch (IOException e) {
            log.error("上传失败",e);
            throw  new LyException(ExceptionEnum.UPLOAD_FILE_ERROR);
        }
    }
}

 

 

代码详解:1.防止恶意文件对文件进行简单的校验

       保证文件后缀名是我们规定的:

      private static  final List<String> ALLOW_TYPES= Arrays.asList("image/jpeg","image/png");
  
    Arrays.asList可以报我们 直接把参数转化成数组元素

         保证文件内容是图片:如果检验到图片则image为空

 

       //校验文件的内容
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image==null){
                throw  new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }

 

 

 

      2.上传图片

        使用transferTo(dest)方法将上传文件写到服务器上指定的文件。

       //保存文件到本地
            File local = new File("F:\\javaee\\IdeaResource\\uploadImg\\",file.getOriginalFilename());
            file.transferTo(local);
            //返回文件地址
            return "http://image.leyou.com/"+file.getOriginalFilename();

 

7测试    

返回地址上传成功

技术分享图片

 

 

 

 

 

leyou_05_文件上传

原文:https://www.cnblogs.com/asndxj/p/11574531.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!