iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >JavaWeb实现文件上传和下载接口功能详解
  • 348
分享到

JavaWeb实现文件上传和下载接口功能详解

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

摘要

目录1.上传java代码实现2.文件流下载java代码实现3.Fileutil工具类代码1.上传java代码实现 @ResponseBody @PostMapping

1.上传java代码实现

    @ResponseBody
    @PostMapping("/upload")
    public ResponseVo upload(@RequestParam(value = "file", required = false) MultipartFile multipartFile) {
        File file=new File("上传到服务器的文件地址");
        try {
            FileUtil.copy(multipartFile.getBytes(), file);
        } catch (ioException e) {
            return  ResultUtil.error();
        }
        return ResultUtil.success();
    }

上传用post或者get请求都可以,这里代码中用post做的示例。

2.文件流下载java代码实现

文件下载除了静态访问(及NginxTomcat等服务器映射到后的文件WEB路径)下载以外 ,还可以通过流的方式下载,代码如下:

    
    @PostMapping("/download")
    public void download(String fileName, httpservletResponse response) throws IOException {
        FileInputStream fis=new FileInputStream("服务器文件所在路径");
        response.addHeader("Content-Disposition", "attachment;filename="+fileName+";"+"filename*=utf-8''"+fileName);
        FileUtil.copy(fis, response.getOutputStream());
    }

上传用post或者get请求都可以,这里代码中用post做的示例。

3.Fileutil工具类代码

import com.tarzan.navigation.common.exception.ForbiddenException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.NonNull;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
 
import java.io.*;
import java.NIO.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
 
@Slf4j
public class FileUtil {
 
    
    public static void copyFolder(@NonNull Path source, @NonNull Path target) throws IOException {
        Assert.notNull(source, "Source path must not be null");
        Assert.notNull(target, "Target path must not be null");
 
        Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
 
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                    throws IOException {
                Path current = target.resolve(source.relativize(dir).toString());
                Files.createDirectories(current);
                return FileVisitResult.CONTINUE;
            }
 
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                    throws IOException {
                Files.copy(file, target.resolve(source.relativize(file).toString()),
                        StandardCopyOption.REPLACE_EXISTING);
                return FileVisitResult.CONTINUE;
            }
        });
    }
 
    
    public static void deleteFolder(@NonNull Path deletingPath) {
        Assert.notNull(deletingPath, "Deleting path must not be null");
 
        if (Files.notExists(deletingPath)) {
            return;
        }
        log.info("Deleting [{}]", deletingPath);
        delete(deletingPath.toFile());
        log.info("Deleted [{}] successfully", deletingPath);
    }
 
    private static void delete(File file) {
        if(file.isDirectory()){
            Arrays.asList(Objects.requireNonNull(file.listFiles())).forEach(FileUtil::delete);
        }
        file.delete();
    }
 
    
    public static void rename(@NonNull Path pathToRename, @NonNull String newName)
            throws IOException {
        Assert.notNull(pathToRename, "File path to rename must not be null");
        Assert.notNull(newName, "New name must not be null");
 
        Path newPath = pathToRename.resolveSibling(newName);
        log.info("Rename [{}] to [{}]", pathToRename, newPath);
 
        Files.move(pathToRename, newPath);
 
        log.info("Rename [{}] successfully", pathToRename);
    }
 
 
 
    
    public static void unzip(@NonNull ZipInputStream zis, @NonNull Path targetPath)
            throws IOException {
        // 1. unzip file to folder
        // 2. return the folder path
        Assert.notNull(zis, "Zip input stream must not be null");
        Assert.notNull(targetPath, "Target path must not be null");
 
        // Create path if absent
        createIfAbsent(targetPath);
 
        // Folder must be empty
       ensureEmpty(targetPath);
 
        ZipEntry zipEntry = zis.getNextEntry();
 
        while (zipEntry != null) {
            // Resolve the entry path
            Path entryPath = targetPath.resolve(zipEntry.getName());
 
            // Check directory
            checkDirectoryTraversal(targetPath, entryPath);
 
            if (zipEntry.isDirectory()) {
                // Create directories
                Files.createDirectories(entryPath);
            } else {
                // Copy file
                Files.copy(zis, entryPath);
            }
 
            zipEntry = zis.getNextEntry();
        }
    }
 
    
    public static void unzip(@NonNull byte[] bytes, @NonNull Path targetPath) throws IOException {
        Assert.notNull(bytes, "Zip bytes must not be null");
 
        ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(bytes));
        unzip(zis, targetPath);
    }
 
    
    public static void zip(@NonNull Path pathToZip, @NonNull Path pathOfArcHive)
            throws IOException {
        try (OutputStream outputStream = Files.newOutputStream(pathOfArchive)) {
            try (ZipOutputStream zipOut = new ZipOutputStream(outputStream)) {
                zip(pathToZip, zipOut);
            }
        }
    }
 
    
    public static void zip(@NonNull Path pathToZip, @NonNull ZipOutputStream zipOut)
            throws IOException {
        // Zip file
        zip(pathToZip, pathToZip.getFileName().toString(), zipOut);
    }
 
    
    private static void zip(@NonNull Path fileToZip, @NonNull String fileName,
                            @NonNull ZipOutputStream zipOut) throws IOException {
        if (Files.isDirectory(fileToZip)) {
            log.debug("Try to zip folder: [{}]", fileToZip);
            // Append with '/' if missing
            String folderName =
                    StringUtils.appendIfMissing(fileName, File.separator, File.separator);
            // Create zip entry and put into zip output stream
            zipOut.putNextEntry(new ZipEntry(folderName));
            // Close entry for writing the next entry
            zipOut.closeEntry();
 
            // Iterate the sub files recursively
            try (Stream<Path> subPathStream = Files.list(fileToZip)) {
                // There should not use foreach for stream as internal zip method will throw
                // IOException
                List<Path> subFiles = subPathStream.collect(Collectors.toList());
                for (Path subFileToZip : subFiles) {
                    // Zip children
                    zip(subFileToZip, folderName + subFileToZip.getFileName(), zipOut);
                }
            }
        } else {
            // Open file to be zipped
            // Create zip entry for target file
            ZipEntry zipEntry = new ZipEntry(fileName);
            // Put the entry into zip output stream
            zipOut.putNextEntry(zipEntry);
            // Copy file to zip output stream
            Files.copy(fileToZip, zipOut);
            // Close entry
            zipOut.closeEntry();
        }
    }
 
    
    public static void createIfAbsent(@NonNull Path path) throws IOException {
        Assert.notNull(path, "Path must not be null");
 
        if (Files.notExists(path)) {
            // Create directories
            Files.createDirectories(path);
 
            log.debug("Created directory: [{}]", path);
        }
    }
 
    
    public static void ensureEmpty(@NonNull Path path) throws IOException {
        if (!isEmpty(path)) {
            throw new DirectoryNotEmptyException("Target directory: " + path + " was not empty");
        }
    }
 
    
    public static void checkDirectoryTraversal(@NonNull String parentPath,
                                               @NonNull String pathToCheck) {
        checkDirectoryTraversal(Paths.get(parentPath), Paths.get(pathToCheck));
    }
 
    
    public static void checkDirectoryTraversal(@NonNull Path parentPath,
                                               @NonNull String pathToCheck) {
        checkDirectoryTraversal(parentPath, Paths.get(pathToCheck));
    }
 
    
    public static void checkDirectoryTraversal(@NonNull Path parentPath,
                                               @NonNull Path pathToCheck) {
        Assert.notNull(parentPath, "Parent path must not be null");
        Assert.notNull(pathToCheck, "Path to check must not be null");
 
        if (pathToCheck.nORMalize().startsWith(parentPath)) {
            return;
        }
 
        throw new ForbiddenException("你没有权限访问 " + pathToCheck);
    }
 
    
    public static boolean isEmpty(@NonNull Path path) throws IOException {
        Assert.notNull(path, "Path must not be null");
 
        if (!Files.isDirectory(path) || Files.notExists(path)) {
            return true;
        }
 
        try (Stream<Path> pathStream = Files.list(path)) {
            return !pathStream.findAny().isPresent();
        }
    }
    
    public static int copy(File in, File out) throws IOException {
        Assert.notNull(in, "No input File specified");
        Assert.notNull(out, "No output File specified");
        return copy(Files.newInputStream(in.toPath()), Files.newOutputStream(out.toPath()));
    }
 
    
    public static void copy(byte[] in, File out) throws IOException {
        Assert.notNull(in, "No input byte array specified");
        Assert.notNull(out, "No output File specified");
        copy(new ByteArrayInputStream(in), Files.newOutputStream(out.toPath()));
    }
 
    
    public static int copy(InputStream in, OutputStream out) throws IOException {
        Assert.notNull(in, "No InputStream specified");
        Assert.notNull(out, "No OutputStream specified");
 
        try {
            return StreamUtils.copy(in, out);
        }
        finally {
            try {
                in.close();
            }
            catch (IOException ex) {
            }
            try {
                out.close();
            }
            catch (IOException ex) {
            }
        }
    }
    
    public static void copy(byte[] in, OutputStream out) throws IOException {
        Assert.notNull(in, "No input byte array specified");
        Assert.notNull(out, "No OutputStream specified");
 
        try {
            out.write(in);
        }
        finally {
            try {
                out.close();
            }
            catch (IOException ex) {
            }
        }
    }
 
 
}

ForbiddenException 访问权限异常类

import org.springframework.Http.HttpStatus;
 

public class ForbiddenException extends RuntimeException {
 
    public ForbiddenException() {
        super();
    }
 
    public ForbiddenException(String message) {
        super(message);
    }
 
    public ForbiddenException(String message, Throwable cause) {
        super(message, cause);
    }
 
    public HttpStatus getStatus() {
        return HttpStatus.FORBIDDEN;
    }
}

图片示例

完整代码请参考:https://gitee.com/taisan/tarzan-navigation

到此这篇关于JAVA WEB实现文件上传和下载接口功能详解的文章就介绍到这了,更多相关Java Web文件上传下载内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: JavaWeb实现文件上传和下载接口功能详解

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

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

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • JavaWeb实现文件上传和下载接口功能详解
    目录1.上传java代码实现2.文件流下载java代码实现3.Fileutil工具类代码1.上传java代码实现 @ResponseBody @PostMapping...
    99+
    2022-12-27
    Java Web文件上传下载 Java Web文件上传 Java Web文件下载 Java 文件上传下载
  • 详解JavaWeb如何实现文件上传和下载功能
    目录1.文件传输原理及介绍2.JavaWeb文件上传2.1我们用一个新的方式创建项目2.2导包2.3实用类介绍2.4pom.xml导入需要的依赖2.5index.jsp2.6info...
    99+
    2024-04-02
  • JavaWeb是如何实现文件上传和下载功能
    这篇文章将为大家详细讲解有关JavaWeb是如何实现文件上传和下载功能,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。1. 文件传输原理及介绍2. JavaWeb文件上传2.1我们用一个新的方...
    99+
    2023-06-22
  • JavaWeb实现文件上传功能详解
    文件上传功能的实现 在大多数网站中,我们都可以看见文件上传和下载功能的实现,今天我们就文件上传做一个详细的总结 实现步骤: 1、新建一个JSP页面:表单必须设置:enctype=&...
    99+
    2024-04-02
  • JavaWeb Servlet实现文件上传与下载功能实例
    目录前言项目准备文件上传前台页面文件下载资源准备超链接下载后台实现下载总结前言 在上网的时候我们常常遇到文件上传的情况,例如上传头像、上传资料等;当然除了上传,遇见下载的情况也很多,...
    99+
    2024-04-02
  • JavaWeb 文件的上传和下载功能简单实现代码
    一、文件的上传和下载1、文件上传的原理分析     1、文件上传的必要前提:          a、提供for...
    99+
    2023-05-31
    java web 文件上传
  • JavaWeb实现上传文件功能
    本文实例为大家分享了JavaWeb实现上传文件的具体代码,供大家参考,具体内容如下 这是需要使用到的两个jar包一定要导入到lib目录中,并添加到发布的lib目录下 index.j...
    99+
    2024-04-02
  • 详解SpringMVC如何实现文件上传和下载功能
    小编这次要给大家分享的是详解SpringMVC如何实现文件上传和下载功能,文章内容丰富,感兴趣的小伙伴可以来了解一下,希望大家阅读完这篇文章之后能够有所收获。本文实例为大家分享了SpringMVC实现文件上传和下载的具体代码,供大家参考,具...
    99+
    2023-05-31
    springmvc 实现文件 如何实现
  • Java+Selenium实现文件上传下载功能详解
    目录简介上传文件下载文件简介 本文主要讲解java代码如何利用selenium操作浏览器上传和下载文件代码教程。 上传文件 常见的 web 页面的上传,一般使用 input 标签或是...
    99+
    2023-01-09
    Java Selenium文件上传下载 Java Selenium文件上传 Java Selenium文件下载 Java Selenium 上传 下载
  • SpringBoot文件上传与下载功能实现详解
    目录前言1、引入Apache Commons FileUpload组件依赖2、设置上传文件大小限制3、创建选择文件视图页面4、创建控制器5、创建文件下载视图页面前言 文件上传与下载是...
    99+
    2022-11-13
    SpringBoot文件上传 SpringBoot文件下载
  • javaweb实现文件上传功能
    本文实例为大家分享了javaweb实现文件上传的具体代码,供大家参考,具体内容如下 1、创建一个空项目 2、新建一个web application 的Module 3、创建一个lib...
    99+
    2024-04-02
  • Vue实现文件上传和下载功能
    本文实例为大家分享了Vue实现文件上传和下载功能的具体代码,供大家参考,具体内容如下 1、a标签download属性 在H5中,为a标签新增了一个download属性,来直接文件的...
    99+
    2024-04-02
  • javaweb实现文件上传小功能
    本文实例为大家分享了javaweb实现文件上传的具体代码,供大家参考,具体内容如下 1.创建文件上传页面 <%@ page contentType="text/html;cha...
    99+
    2024-04-02
  • JavaWeb实现文件的上传与下载
    JavaWeb实现文件的上传与下载,供大家参考,具体内容如下 第一步:导包 导入commons-fileupload-1.3.3.jar和commons-io-2.4.jar两个依赖...
    99+
    2024-04-02
  • java实现文件上传下载功能
    本文实例为大家分享了java实现文件上传下载的具体代码,供大家参考,具体内容如下 1.上传单个文件 Controller控制层 import java.io.File; imp...
    99+
    2024-04-02
  • SpringMVC实现文件上传下载功能
    目录导入需要的依赖包一、单个文件上传二、多个文件上传三、上传文件列表显示四、文件下载今天遇到文件上传的问题,使用Ajax方式进行提交,服务器一直报错The current reque...
    99+
    2024-04-02
  • JavaWeb实现简单文件上传功能
    本文实例为大家分享了JavaWeb实现简单文件上传的具体代码,供大家参考,具体内容如下 1.概述 通常浏览器上传的所有参数,我们可以通过request对象的getParameter ...
    99+
    2024-04-02
  • JavaWeb实现简单上传文件功能
    本文实例为大家分享了JavaWeb实现上传文件功能的具体代码,供大家参考,具体内容如下 基本思想:网站服务器的内部除了有Web应用,还有文件系统,客户端向网站上传文件就是将文件以流的...
    99+
    2024-04-02
  • JavaWeb如何实现上传文件功能
    本篇内容主要讲解“JavaWeb如何实现上传文件功能”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“JavaWeb如何实现上传文件功能”吧!这是需要使用到的两个jar包一定要导入到lib目录中,并...
    99+
    2023-07-02
  • javaweb怎么实现文件上传功能
    本文小编为大家详细介绍“javaweb怎么实现文件上传功能”,内容详细,步骤清晰,细节处理妥当,希望这篇“javaweb怎么实现文件上传功能”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。创建文件上传页面<%...
    99+
    2023-07-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作