java实现上传下载ftp

上传、下载

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, "下载出现未知错误。");
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_37310913/article/details/86611372