springboot实现excel文件的上传和下载

本文详细介绍使用Java实现文件上传和下载的过程,包括Maven依赖配置、页面代码编写、Spring框架下MultipartConfigElement配置、控制器中文件上传及下载功能实现。通过具体代码示例,展示了如何处理文件上传路径、上传文件名、文件是否存在判断及异常处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我发现我好笨啊,搞了这么久。。。

首先pom文件导入如下:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.16</version>
</dependency>

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.16</version>
</dependency>

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

接着就开始写了,我用了页面作为测试,页面代码如下;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>成功页面。。。</h1>
<form action="file/upup" method="post" enctype="multipart/form-data">
<p>文件上传</p>
<input type="file" name="file">
<p><input type="submit" value="提交"></p>
</form>
<a href="/download">下载</a>
</body>
</html>

接着application.java这个启动文件写如下;

public static String  tempPath="D://images/";
 @Bean
MultipartConfigElement multipartConfigElement(){
    MultipartConfigFactory factory = new MultipartConfigFactory();
    factory.setLocation(tempPath);
     return factory.createMultipartConfig();

}

接着就是控制器的写法了,上传和下载的代码如下;

上传的;

@ResponseBody
@RequestMapping("file/upup")
public TaotaoResult upup(@RequestParam("file")MultipartFile file,
                         HttpServletRequest request){
    if(!file.isEmpty())
    {
        String  pa="D:/images/";
         path=request.getServletContext().getRealPath("");
        //上传文件名
        String filename=file.getOriginalFilename();
        File filepath=new File(path,filename);
        //判断路劲是否存在,如果不存在就创建一个
        if (!filepath.getParentFile().exists()){
            filepath.getParentFile().mkdirs();
        }
        //将上传文件保存到一个目标文件当中
        try {
            file.transferTo(new File(pa+File.separator+filename));
            return TaotaoResult.ok("文件上传成功");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }else {
        return TaotaoResult.ok("文件为空,请重新上传");
    }
      return TaotaoResult.ok("异常");

}

下载的:

@ResponseBody
@RequestMapping("/download")
public TaotaoResult downloadFile(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {

    // 获取指定目录下的第一个文件
    File scFileDir = new File("D://images");
    File TrxFiles[] = scFileDir.listFiles();
    System.out.println(TrxFiles[0]);
    String fileName = TrxFiles[0].getName(); //下载的文件名

    // 如果文件名不为空,则进行下载
    if (fileName != null) {
        //设置文件路径
        String realPath = "D://images/";
        File file = new File(realPath, fileName);

        // 如果文件名存在,则进行下载
        if (file.exists()) {

            // 配置文件下载
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

            // 实现文件下载
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                System.out.println("Download the song successfully!");
            }
            catch (Exception e) {
                System.out.println("Download the song failed!");
            }
            finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    return TaotaoResult.ok("成功");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值