文件上传与文件下载

文件上传与文件下载
在开发中项目难免会遇到文件上传和下载的情况,如果公司有部署文件服务器是再好不过啦,直接调用文件服务器上传和下载的接口,保留返回的文件id即可。
但是如果公司没有文件服务器就比较苦逼了,得手写文件上传和下载的接口把文件存储在服务器的某个位置,以便使用。
直接把代码贴出来以供记录笔记。
首先controller层

@ApiOperation(value = "文件上传", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @PostMapping("/file/upload")
    @Transactional(rollbackFor = Exception.class)
    public ApiResult<String> upload(@RequestPart("file") MultipartFile file) {
    
    
        try {
    
    
            TFileUploadDet fileUpload = FileManageUtil.upload(file);
            return  ApiResult.data(fileUpload.getId());
        } catch (Exception e) {
    
    
            log.error(e.getMessage(),e);
            return ApiResult.fail(e.getMessage());
        }
    }

然后服务层

public static TFileUploadDet upload(MultipartFile file) {
    
    
        Assert.notNull(file, "文件不能为空");
		//获取上传文件名称
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf('.'));
        String extName = suffix.substring(1);
        //校验文件格式是否为规定
        Assert.isTrue(WjlxEnum.WJLX999.getExtNameList().contains(extName),"文件类型仅支持jpg/mp4/pdf,请确认!");
        String id = SecureUtil.md5(originalFilename + IdUtil.getSnowflakeNextIdStr());
        String fileName = id + suffix;
        String year = DateUtil.format(new Date(), "yyyy");
        String today = DateUtil.format(new Date(), "yyyy-MM-dd");
        //获取文件存储路径
        String fileId = File.separator + year + File.separator + today + File.separator + fileName;
        Path path = Paths.get(filePath(fileId));
        //创建文件夹(存在文件夹就直接存在该文件夹下没有文件夹就先创建文件夹在保存)
        FileUtil.mkParentDirs(path);

        InputStream inputStream = null;
        OutputStream outputStream = null;
		//文件流上传文件
        try {
    
    
            inputStream = file.getInputStream();
            outputStream = Files.newOutputStream(path);
            IoUtil.copy(inputStream, outputStream);
            //一下为自定义返回参数,视情况而定
            TFileUploadDet fileUpload = new TFileUploadDet();
            fileUpload.setId(id);
            fileUpload.setWjmc(originalFilename);
            fileUpload.setWjlj(path.toString());
            fileUpload.setCreateTime(new Date());
            return fileUpload;
        } catch (IOException e) {
    
    
            throw new RuntimeException("文件上传失败", e);
        } finally {
    
    
            IoUtil.close(outputStream);
            IoUtil.close(inputStream);
        }
    }

/**
     * 获取完整的文件路径
     *
     * @param fileId 文件唯一标识
     * @return 文件路径
     */
    public static String filePath(String fileId) {
    
    
        return uploadFilePath + fileId;
    }

注:需要注意的是 获取完整文件路径方法中的 uploadFilePath :是文件将要保存在服务器中的位置路径,可以在配置文件中配置好后引用。最后把返回的信息存在在表中使用。整个文件上传就完成了。其中用到了hutool的第三方包我使用的版本为5.8.6

	<dependency>
                <groupId>cn.hutool</groupId>
                <artifactId>hutool-core</artifactId>
                <version>5.8.6</version>
            </dependency>

文件下载

这个就没有什么好说的了,比较简单,就是流的操作而已。传入的参数为文件上传是保存的文件的id即可。

	@ApiOperation(value = "通过文件id下载文件")
    @PostMapping("/downloadById")
    public void downloadFileById(HttpServletRequest request, HttpServletResponse response, @RequestBody @Valid IdDTO idDTO) {
    
    
        String id = idDTO.getId();
        Assert.isTrue(StringUtils.isNotEmpty(id), "主表id不能为空");
        TFile tFile = fileService.getById(id);
        Assert.notNull(tFile, "要下载的文件不存在");
        String fileName = tFile.getFileName();
        request.getSession();

        //获取页面输出流
        try (ServletOutputStream out = response.getOutputStream()) {
    
    
            String path = tFile.getFileLink();
            File file = new File(path);
            byte[] bytes = FileUtils.readFileToByteArray(file);

            // 设置响应头
            response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");

            out.write(bytes);
            out.flush();
        } catch (IOException e) {
    
    
            log.error(e.getMessage());
            throw new RuntimeException("下载文件出错");
        }
    }

学习笔记仅供参考!

猜你喜欢

转载自blog.csdn.net/weixin_51114236/article/details/131190578