JAVA 文件上传下载(网络文件和本地文件)

上传

/**
     * 文件上传
     * @param file
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation(value = "文件上传")
    @ApiOperationSupport(order = 1)
    @RequiresPermissions("baseinfo:basic-information:upload")
    public RestApiResponse<FileBasicInformation> upload(MultipartFile file) {
        ruleCheck(file);
        String originalFilename = file.getOriginalFilename();
        if (!originalFilename.contains(FILE_SPLIT)) {
            throw new SysException("缺少后缀名");
        }
        String name = originalFilename.substring(0,originalFilename.indexOf(FILE_SPLIT));
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(FILE_SPLIT));
        String timeStr = formatDate(new Date(), "yyyyMMdd HHmmss");
        String folder = File.separator + BASIC_FILE_DIR + File.separator + timeStr.substring(0,8) + File.separator;
        String path = folder + name + timeStr.substring(9) + suffix;
        try {
            FileUtils.saveFile(file, path);
        } catch (IOException e) {
            throw new SysException("文件保存错误");
        }
        FileBasicInformation fileBasicInformation = new FileBasicInformation();;
        fileBasicInformation.setParent(fileConfig.getSaveDir());
        fileBasicInformation.setName(originalFilename);
        fileBasicInformation.setUrl(path);
        fileBasicInformation.setSize(file.getSize());
        fileBasicInformation.setType(file.getContentType());
        Long id = fileBasicInformationService.insert(fileBasicInformation);
        return RestApiResponse.success(fileBasicInformation);
    }

    
    public static void saveFile(MultipartFile file, String path) throws IOException {
        Path filePath = Paths.get(fileConfig.getSaveDir(), path);
        final Path dir = filePath.getParent();
        if (!Files.exists(dir)) {
            Files.createDirectories(dir);
        }
        // 存储方法
        file.transferTo(filePath.toFile());
    }


TransferTo 方法

在文件上传的时候,MultipartFile中的transferTo(dest)方法只能使用一次;

并且使用transferTo方法之后不可以在使用getInputStream()方法;

否则再使用getInputStream()方法会报异常java.lang.IllegalStateException: File has been moved - cannot be read again;

使用transferTo(dest)方法将上传文件写到服务器上指定的文件;

原因文件流只可以接收读取一次,传输完毕则关闭流;

 

下载

/**
     * @description 文件下载-写汇流到前端
     * @param fileName 文件名(带后缀)
     * @param url 文件远程地址/文件存储地址完整路径
     * @param response
     */
    public static void download(String fileName, String url, HttpServletResponse response) throws UnsupportedEncodingException {
        response.setContentType("application/force-download");
        response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
        InputStream ins = null;
        OutputStream os = null;
        File file = new File(url);
        try {
            // 本地文件
            if (file.exists()) {
                ins = new FileInputStream(file);
            } else {
                // 网络文件
                URL urlFile = null;
                urlFile = new URL(url);
                // 输入流
                ins = urlFile.openStream();
            }
            os = response.getOutputStream();
            int len;
            while ((len = ins.read()) != -1) {
                os.write(len);
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }finally {
            try {
                os.flush();
                ins.close();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

 

Guess you like

Origin blog.csdn.net/huofuman960209/article/details/118142277