java实现上传下载ftp

本文详细介绍了如何使用Java实现文件的上传与下载功能,包括处理文件名、大小及类型,利用MultipartFile进行文件读取,以及通过HttpServletResponse完成文件下载过程。

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

上传、下载

public Result upFile(MultipartFile file, @RequestParam int mid) {
        System.out.println("开始上传=======================");
        System.out.println("开始上传=======================");
        System.out.println("file name=" + file.getName());
        System.out.println("origin file name=" + file.getOriginalFilename());
        System.out.println("file size=" + file.getSize());

        try {
            File localFile = new File(filePath,
                    StringUtils.substringBefore(file.getOriginalFilename(),
                            ".") + "mid=" + mid + ".txt");
            file.transferTo(localFile);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "文件上传失败。");
        }
        return new Result(true, StatusCode.OK, "文件上传成功。");
    }


public Result fileDownload(String fileName, HttpServletResponse response) {
        try (
                //自动关闭流
                InputStream inputStream = new FileInputStream(new File(filePath, fileName + ".txt"));
                OutputStream outputStream = response.getOutputStream()
        ) {
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;fileName=" +
                    new String(fileName.getBytes(),
                            StandardCharsets.ISO_8859_1) + ".txt");   // 设置文件名(中文名会变成下划线时因为浏览器只支持ISO-8859-1的编码格式不支持UTF-8)
            //把输入流copy到输出流
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
            return new Result(true, StatusCode.OK, "下载成功。");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "下载失败,文件未找到。");
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "下载失败,流异常。");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "下载出现未知错误。");
        }
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值