返回顶部
首页 > 资讯 > 后端开发 > Python >SpringBoot实现单文件与多文件上传
  • 665
分享到

SpringBoot实现单文件与多文件上传

2024-04-02 19:04:59 665人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

目录一、公共文件存储代码1.FileUploadUtils.java2.FileUtils.java3.MimeTypeUtils.java4.FileException.java5

一、公共文件存储代码

1.FileUploadUtils.java


package com.SpringCloud.blog.admin.util.file;



import com.springcloud.blog.admin.exception.file.FileNameLengthLimitExceededException;
import com.sprinGCloud.blog.admin.exception.file.FileSizeLimitExceededException;
import com.springcloud.blog.admin.exception.file.InvalidExtensionException;
import com.springcloud.blog.admin.util.DateUtils;
import com.springcloud.blog.admin.util.IdUtils;
import com.springcloud.blog.admin.util.StringUtils;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.io.FilenameUtils;
import org.springframework.WEB.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

public class FileUploadUtils {
    
    public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024;

    
    public static final int DEFAULT_FILE_NAME_LENGTH = 100;

    
    private static String defaultBaseDir = "D://test//";

    
    public static String resource_prefix = "D://test//";

    public static void setDefaultBaseDir(String defaultBaseDir) {
        FileUploadUtils.defaultBaseDir = defaultBaseDir;
    }

    public static String getDefaultBaseDir() {
        return defaultBaseDir;
    }

    
    public static final String upload(MultipartFile file) throws IOException {
        try {
            return upload(getDefaultBaseDir(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }


    
    public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension)
            throws FileUploadBase.FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
            InvalidExtensionException {
        int fileNamelength = file.getOriginalFilename().length();
        if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
            throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
        }

        assertAllowed(file, allowedExtension);

        String fileName = extractFilename(file);

        File desc = getAbsoluteFile(baseDir, fileName);
        file.transferTo(desc);
        String pathFileName = getPathFileName(baseDir, fileName);
        return pathFileName;
    }

    
    public static final String extractFilename(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String extension = getExtension(file);
        fileName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension;
        return fileName;
    }

    private static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException {
        File desc = new File(uploadDir + File.separator + fileName);

        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        if (!desc.exists()) {
            desc.createNewFile();
        }
        return desc;
    }

    private static final String getPathFileName(String uploadDir, String fileName) throws IOException {
        int dirLastIndex = defaultBaseDir.length() + 1;
        String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
        String pathFileName = resource_prefix + "/" + currentDir + "/" + fileName;
        return pathFileName;
    }

    
    public static final void assertAllowed(MultipartFile file, String[] allowedExtension)
            throws FileSizeLimitExceededException, InvalidExtensionException {
        long size = file.getSize();
        if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE) {
            throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024);
        }

        String fileName = file.getOriginalFilename();
        String extension = getExtension(file);
        if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) {
            if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION) {
                throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension,
                        fileName);
            } else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION) {
                throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension,
                        fileName);
            } else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION) {
                throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension,
                        fileName);
            } else if (allowedExtension == MimeTypeUtils.VIDEO_EXTENSION) {
                throw new InvalidExtensionException.InvalidVideoExtensionException(allowedExtension, extension,
                        fileName);
            } else {
                throw new InvalidExtensionException(allowedExtension, extension, fileName);
            }
        }

    }

    
    public static final boolean isAllowedExtension(String extension, String[] allowedExtension) {
        for (String str : allowedExtension) {
            if (str.equalsIgnoreCase(extension)) {
                return true;
            }
        }
        return false;
    }

    
    public static final String getExtension(MultipartFile file) {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StringUtils.isEmpty(extension)) {
            extension = MimeTypeUtils.getExtension(file.getContentType());
        }
        return extension;
    }
}

2.FileUtils.java


package com.springcloud.blog.admin.util.file;

import javax.servlet.Http.httpservletRequest;
import java.io.*;
import java.net.URLEncoder;


public class FileUtils extends org.apache.commons.io.FileUtils {
    public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";

    
    public static void writeBytes(String filePath, OutputStream os) throws IOException {
        FileInputStream fis = null;
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                throw new FileNotFoundException(filePath);
            }
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0) {
                os.write(b, 0, length);
            }
        } catch (IOException e) {
            throw e;
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    
    public static boolean deleteFile(String filePath) {
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    
    public static boolean isValidFilename(String filename) {
        return filename.matches(FILENAME_PATTERN);
    }

    
    public static String setFileDownloadHeader(HttpServletRequest request, String fileName)
            throws UnsupportedEncodingException {
        final String agent = request.getHeader("USER-AGENT");
        String filename = fileName;
        if (agent.contains("MSIE")) {
            // IE浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        } else if (agent.contains("Firefox")) {
            // 火狐浏览器
            filename = new String(fileName.getBytes(), "ISO8859-1");
        } else if (agent.contains("Chrome")) {
            // Google浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        } else {
            // 其它浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }
}

3.MimeTypeUtils.java


package com.springcloud.blog.admin.util.file;


public class MimeTypeUtils {
    public static final String IMAGE_PNG = "image/png";

    public static final String IMAGE_JPG = "image/jpg";

    public static final String IMAGE_JPEG = "image/jpeg";

    public static final String IMAGE_BMP = "image/bmp";

    public static final String IMAGE_GIF = "image/gif";

    public static final String[] IMAGE_EXTENSION = {"bmp", "gif", "jpg", "jpeg", "png"};

    public static final String[] FLASH_EXTENSION = {"swf", "flv"};

    public static final String[] MEDIA_EXTENSION = {"swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg",
            "asf", "rm", "rmvb"};

    public static final String[] VIDEO_EXTENSION = {"mp4", "avi", "rmvb"};

    public static final String[] DEFAULT_ALLOWED_EXTENSION = {
            // 图片
            "bmp", "gif", "jpg", "jpeg", "png",
            // Word excel powerpoint
            "doc", "docx", "xls", "xlsx", "ppt", "pptx", "html", "htm", "txt",
            // 压缩文件
            "rar", "zip", "gz", "bz2",
            // 视频格式
            "mp4", "avi", "rmvb",
            // pdf
            "pdf"};

    public static String getExtension(String prefix) {
        switch (prefix) {
            case IMAGE_PNG:
                return "png";
            case IMAGE_JPG:
                return "jpg";
            case IMAGE_JPEG:
                return "jpeg";
            case IMAGE_BMP:
                return "bmp";
            case IMAGE_GIF:
                return "gif";
            default:
                return "";
        }
    }
}

4.FileException.java


package com.springcloud.blog.admin.exception.file;

import com.springcloud.blog.admin.exception.BaseException;


public class FileException extends BaseException {
    private static final long serialVersionUID = 1L;

    public FileException(String code, Object[] args) {
        super("file", code, args, null);
    }

}

5.FileNameLengthLimitExceededException.java


package com.springcloud.blog.admin.exception.file;


public class FileNameLengthLimitExceededException extends FileException {
    private static final long serialVersionUID = 1L;

    public FileNameLengthLimitExceededException(int defaultFileNameLength) {
        super("upload.filename.exceed.length", new Object[]{defaultFileNameLength});
    }
}

6.FileSizeLimitExceededException.java


package com.springcloud.blog.admin.exception.file;


public class FileSizeLimitExceededException extends FileException {
    private static final long serialVersionUID = 1L;

    public FileSizeLimitExceededException(long defaultMaxSize) {
        super("upload.exceed.maxSize", new Object[]{defaultMaxSize});
    }
}

7.InvalidExtensionException.java


package com.springcloud.blog.admin.exception.file;



import org.apache.commons.fileupload.FileUploadException;

import java.util.Arrays;

public class InvalidExtensionException extends FileUploadException {
    private static final long serialVersionUID = 1L;

    private String[] allowedExtension;
    private String extension;
    private String filename;

    public InvalidExtensionException(String[] allowedExtension, String extension, String filename) {
        super("filename : [" + filename + "], extension : [" + extension + "], allowed extension : [" + Arrays.toString(allowedExtension) + "]");
        this.allowedExtension = allowedExtension;
        this.extension = extension;
        this.filename = filename;
    }

    public String[] getAllowedExtension() {
        return allowedExtension;
    }

    public String getExtension() {
        return extension;
    }

    public String getFilename() {
        return filename;
    }

    public static class InvalidImageExtensionException extends InvalidExtensionException {
        private static final long serialVersionUID = 1L;

        public InvalidImageExtensionException(String[] allowedExtension, String extension, String filename) {
            super(allowedExtension, extension, filename);
        }
    }

    public static class InvalidFlashExtensionException extends InvalidExtensionException {
        private static final long serialVersionUID = 1L;

        public InvalidFlashExtensionException(String[] allowedExtension, String extension, String filename) {
            super(allowedExtension, extension, filename);
        }
    }

    public static class InvalidMediaExtensionException extends InvalidExtensionException {
        private static final long serialVersionUID = 1L;

        public InvalidMediaExtensionException(String[] allowedExtension, String extension, String filename) {
            super(allowedExtension, extension, filename);
        }
    }

    public static class InvalidVideoExtensionException extends InvalidExtensionException {
        private static final long serialVersionUID = 1L;

        public InvalidVideoExtensionException(String[] allowedExtension, String extension, String filename) {
            super(allowedExtension, extension, filename);
        }
    }
}

8.BaseException.java


package com.springcloud.blog.admin.exception;


public class BaseException extends RuntimeException {
    private static final long serialVersionUID = 1L;

    
    private String module;

    
    private String code;

    
    private Object[] args;

    
    private String defaultMessage;

    public BaseException(String module, String code, Object[] args, String defaultMessage) {
        this.module = module;
        this.code = code;
        this.args = args;
        this.defaultMessage = defaultMessage;
    }

    public BaseException(String module, String code, Object[] args) {
        this(module, code, args, null);
    }

    public BaseException(String module, String defaultMessage) {
        this(module, null, null, defaultMessage);
    }

    public BaseException(String code, Object[] args) {
        this(null, code, args, null);
    }

    public BaseException(String defaultMessage) {
        this(null, null, null, defaultMessage);
    }

    public String getModule() {
        return module;
    }

    public String getCode() {
        return code;
    }

    public Object[] getArgs() {
        return args;
    }

    public String getDefaultMessage() {
        return defaultMessage;
    }
}

二、单文件上传代码


@PostMapping("/post/uploadFile")
@apiOperation("文章上传特色图片")
public ResponseBaseDTO<String> uploadFile(@RequestParam("file") MultipartFile file) {
    logger.info("/post/uploadFile");
    try {

        String fileUrl = FileUploadUtils.upload(file);
        if (fileUrl != null) {
            return ResponseBaseDTO.createSuccResp(fileUrl);
        }
        return ResponseBaseDTO.createFailResp(fileUrl);
    } catch (Exception e) {
        logger.error("/post/uploadFile", e);
        return ResponseBaseDTO.createFailResp(e.getMessage());
    }
}

三、多文件上传代码


@PostMapping("/batchImportsUsers")
@ApiOperation("批量导入用户数据小时")
public ResponseBaseDTO<String> batchImportsUsers(MultipartFile[] uploadFiles) {
    if (uploadFiles.length > 0) {
        for (int i = 0; i < uploadFiles.length; i++) {
            try {
                importUserExcelData(uploadFiles[i]);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ResponseBaseDTO.createSuccResp();
    }
    return ResponseBaseDTO.createFailResp(e.getMessage());
}

以上就是SpringBoot实现单文件与多文件上传的详细内容,更多关于SpringBoot文件上传的资料请关注编程网其它相关文章!

--结束END--

本文标题: SpringBoot实现单文件与多文件上传

本文链接: https://lsjlt.com/news/126690.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

猜你喜欢
  • SpringBoot实现单文件与多文件上传
    目录一、公共文件存储代码1.FileUploadUtils.java2.FileUtils.java3.MimeTypeUtils.java4.FileException.java5...
    99+
    2024-04-02
  • SpringBoot实现单文件与多文件上传功能
    目录1.单文件上传2.多文件上传1.单文件上传 首先创建一个Spring Boot项目,并添加spring-boot-starter-web依赖 然后创建一个upload.jsp文件...
    99+
    2024-04-02
  • SpringBoot如何实现单文件与多文件上传功能
    这篇文章将为大家详细讲解有关SpringBoot如何实现单文件与多文件上传功能,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。1.单文件上传首先创建一个Spring Boot项目,并添加spring-boo...
    99+
    2023-06-26
  • SpringMVC 单文件上传与多文件上传实例
    一、简述一个javaWeb项目中,文件上传功能几乎是必不可少的,本人在项目开发中也时常会遇到,以前也没怎么去理它,今天有空学习了一下这方面的知识,于是便将本人学到的SpringMVC中单文件与多文件上传这部分知识做下笔记。二、单文件上传1、...
    99+
    2023-05-31
    springmvc 文件上传 多文件上传
  • SpringBoot简单实现文件上传
    目录1.创建SpringBoot项目2.修改application.properties配置文件3.编写控制器UserController类4.编写前端页面index.html5.效...
    99+
    2024-04-02
  • java如何实现单文件与多文件上传功能
    小编给大家分享一下java如何实现单文件与多文件上传功能,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!java 文件上传(单文件与多文件)一、简述一个javaWe...
    99+
    2023-05-30
    java
  • SpringBoot如何实现多文件上传
    这篇文章主要介绍“SpringBoot如何实现多文件上传”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“SpringBoot如何实现多文件上传”文章能帮助大家解决问题。1.代码结构:2.Control...
    99+
    2023-07-05
  • springboot多文件上传实现使用postman测试多文件上传接口
    使用postman测试多文件上传接口 1、创建测试类(FileController.java) package com.jeff.controller; import java....
    99+
    2024-04-02
  • Struts2实现单文件或多文件上传功能
    一、简述Struts2的文件上传其实也是通过拦截器来实现的,只是该拦截器定义为默认拦截器了,所以不用自己去手工配置,<interceptor name="fileUpload" class="org.apache.struts2.in...
    99+
    2023-05-31
    struts2 文件上传 st
  • Spring boot实现文件上传实例(多文件上传)
    文件上传主要分以下几个步骤:(1)新建maven java project;(2)在pom.xml加入相应依赖;(3)新建一个表单页面(这里使用thymleaf);(4)编写controller;(5)测试;(6)对上传的文件做一些限制;(...
    99+
    2023-05-31
    spring boot 文件上传
  • 【SpringBoot+MyBatisPlus】文件上传与文件下载的应用与实现
    文章目录 前言一.文件上传二.改进三.文件下载四.上传图片/回显图片 前言 一次“上传文件”的点击蕴含着一轮请求,我们要做的就是针对每一次的请求进行i/o处理,并返回给前端用户 一.文...
    99+
    2023-09-08
    spring boot java mybatis
  • springboot多文件上传如何实现使用postman测试多文件上传接口
    这篇文章给大家分享的是有关springboot多文件上传如何实现使用postman测试多文件上传接口的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。使用postman测试多文件上传接口1、创建测试类(FileCon...
    99+
    2023-06-20
  • Springboot实现上传文件,并实现调用第三方接口post请求多文件上传文件
    项目过程中,经常会有和第三方接口打交道的过程,今天实现调用第三方上传文件的接口!! 通常拿到第三方的接口文档的时候,不是第一时间先写代码,而是详细阅读接口文档。若接口需要第三方提供的基本参数,例如si...
    99+
    2023-09-08
    spring boot java 后端 spring
  • SpringBoot实现文件上传功能
    经典的文件上传 服务器处理上传文件一般都是先在请求中读取文件信息,然后改变名称保存在服务器的临时路径下,最后保存到服务器磁盘中。本次以thymeleaf搭建demo,因此需要引入th...
    99+
    2024-04-02
  • 怎么用node+multer中间件实现单文件、多文件上传
    本篇内容介绍了“怎么用node+multer中间件实现单文件、多文件上传”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能...
    99+
    2024-04-02
  • ASP.NETCore实现多文件上传
    创建应用程序 打开VS 2017   --新建 ASP.NET Core Web 应用程序     --Web 应用程序(模型视图控制器) 程序名字、路径,默认即可 删除不必要的内...
    99+
    2024-04-02
  • 简单实现Android文件上传
    文件上传在B/S应用中是一种十分常见的功能,那么在Android平台下是否可以实现像B/S那样的文件上传功能呢?答案是肯定的。下面是一个模拟网站程序上传文件的例子。 首先新...
    99+
    2022-06-06
    Android
  • javaWeb实现简单文件上传
    本文实例为大家分享了javaWeb实现简单文件上传的具体代码,供大家参考,具体内容如下 1.先导入两个包:commons-fileupload-1.3.3.jar,commons-i...
    99+
    2024-04-02
  • springboot集成ftp实现文件上传
    本文实例为大家分享了springboot集成ftp实现文件上传的具体代码,供大家参考,具体内容如下 1、FileUtil package io.renren.modules.os...
    99+
    2024-04-02
  • Springboot文件上传功能的实现
    目录1.新建文件上传页面2.新建文件上传处理Controller类3.文件上传功能测试4.文件上传路径回显5.多文件上传功能实现6.文件名不同时的多文件上传处理1.新建文件上传页面 ...
    99+
    2023-05-15
    springboot文件上传 springboot文件上传方法
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作