栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

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

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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

1.pom

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

 
        org.springframework.boot
        spring-boot-starter-parent
        2.4.5
         
    
    
        UTF-8
        UTF-8
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-test
        

    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

新建得FileUpload服务得pom

 
        
            com.spring4all
            swagger-spring-boot-starter
            1.7.0.RELEASE
        

        
            com.github.xiaoymin
            swagger-bootstrap-ui
            1.9.6
        
        
            cn.hutool
            hutool-all
            5.6.3
        
    
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


            cn.hutool
            hutool-all
            5.6.3
 
Controller层
	
	@ApiOperation(value="上传文件夹", notes="上传文件夹接口")
	@RequestMapping(value="/upload", method = RequestMethod.POST)
	public void upload( @RequestParam(value = "multipartFile") MultipartFile[] multipartFile) throws IOException {
		Map map = new HashMap();
		map = fileService.uploadFiles(multipartFile);
		System.out.println(map);
	}
Service层
 public Map uploadFiles(MultipartFile[] multipartFile) throws IOException {
        Map map = new HashMap();
        //获取当前项目所在路径
        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;
        }
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/959991.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号