.net转Java学习笔记16-多文件上传和zip打包下载1-MultipartFile类运用文件上传

一个新需求,文件进行算法自动标注,上传几张图片 平台进行标注后将标注之后得图片进行重新下载,需求分成一下三点
1.多文件上传,将需要标注得图片上传到服务器得临时区域,每次上传都先删除上传上传得临时文件,防止垃圾文件冗余
2.算法标注,将标注后得算法结果内容放在临时文件区
3.将多个结果文件进行zip打包,然后进行下载

其中1 3 涉及文件上传和下载,网上通用代码得工具类整理记录下

1.pom

这边之前建立过父工程和子工程
父工程pom

 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</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>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

新建得FileUpload服务得pom

 <dependencies>
        <dependency>
            <groupId>com.spring4all</groupId>
            <artifactId>swagger-spring-boot-starter</artifactId>
            <version>1.7.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.6</version>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.6.3</version>
        </dependency>
    </dependencies>

2.application.yml

server:
  port: 8021

spring:
  application:
    name: fileUpload
  devtools:
    restart:
      enabled: true  #设置开启热部署
  servlet:
    multipart:
      enabled: true
      max-file-size: 1000MB
      max-request-size: 2000MB
      file-size-threshold: 512KB

这边不加multipart得设置文件得话,文件上传就会限制在1M以内,超过1M就会报错

Spring Boot:The field file exceeds its maximum permitted size of 1048576 bytes.

在这里插入图片描述

3.Swagger2

package com.liutao.config;

import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI
public class Swagger2 {
	@Bean
	public Docket createRestApi() {
		return new Docket(DocumentationType.SWAGGER_2)
				.apiInfo(apiInfo())
				.select()
				.apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
				.paths(PathSelectors.any())
				.build();
	}

	private ApiInfo apiInfo() {
		return new ApiInfoBuilder()
				.title("接口文档")
				.description("模型数据联动接口文档")
				.version("1.0")
				.contact(new Contact("刘涛", "", "1299828500@qq.com"))
				.build();
	}

}

4.文件上传代码

文件上传得核心代码就是四行

  // 创建文件名称
  String fileName = UUID.randomUUID() + "." + multipartFile[i].getContentType()
              .substring(multipartFile[i].getContentType().lastIndexOf("/") + 1);
  String filePath = path +"//"+fileName;
  // 创建文件
  File saveFile = new File(filePath);
  // 文件保存
  multipartFile[i].transferTo(saveFile);

主要就是MultipartFile得使用,详细可以看
MultipartFile与File的一些事

什么是MultipartFile
MultipartFile是spring类型,代表HTML中form data方式上传的文件,包含二进制数据+文件名称。【来自百度知道】

如果出现中文乱码可以参考这个
HttpClient上传文件中文名乱码

因为我这边是需要多文件上传,然后存放在临时区域,每次上传都需要删除原来得文件夹,所以涉及一些file操作和文件上传得无关,用的是hutool工具类中得FileUtil

<dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.6.3</version>
 </dependency>

Controller层

	/**
	 * 文件上传
	 *
	 * @param multipartFile
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	@ApiOperation(value="上传文件夹", notes="上传文件夹接口")
	@RequestMapping(value="/upload", method = RequestMethod.POST)
	public void upload( @RequestParam(value = "multipartFile") MultipartFile[] multipartFile) throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		map = fileService.uploadFiles(multipartFile);
		System.out.println(map);
	}

Service层

 public Map<String, Object> uploadFiles(MultipartFile[] multipartFile) throws IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        //获取当前项目所在路径
        ApplicationHome home = new ApplicationHome();
        File jarFile = home.getSource();
        String  path = jarFile.getParent()+"\\temp";
        //每次对临时文件夹进行删除 重新生成 保证数据不会冗余
        if (FileUtil.exist(path)) {
            FileUtil.del(path );
        }
        FileUtil.mkdir(path );
        if (multipartFile != null && multipartFile.length > 0) {
            for (int i = 0; i < multipartFile.length; i++) {
                // 创建文件名称
                String fileName = UUID.randomUUID() + "." + multipartFile[i].getContentType()
                        .substring(multipartFile[i].getContentType().lastIndexOf("/") + 1);
                String filePath = path +"\\"+fileName;
                // 创建文件
                File saveFile = new File(filePath);
                // 文件保存
                multipartFile[i].transferTo(saveFile);

                // 返回信息 打印控制台
                map.put("fileame", multipartFile[i].getName());  // 设置文件名称
                map.put("contentType", multipartFile[i].getContentType());   // 设置文件类型
                map.put("fileSize", multipartFile[i].getSize()); // 设置文件大小
                map.put("filePath", filePath);  // 保存文件的路径信息
            }
            return map;
        } else {
            map.put("msg","no file");
            return map;
        }
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值