File upload and file download

File upload and file download
It is inevitable that the project will encounter file upload and download during development. If the company has deployed a file server, it would be great, just call the file server upload and download interface directly, and keep the returned file id.
But if the company does not have a file server, it will be more difficult, and the interface for uploading and downloading files must be handwritten to store the files in a certain location on the server for easy use.
Paste the code directly for your notes.
First the controller layer

@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());
        }
    }

then the service layer

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;
    }

Note: It should be noted that uploadFilePath in the method of obtaining the complete file path: it is the location path where the file will be saved in the server, which can be referenced after configuration in the configuration file. Finally, the returned information is stored in the table for use. The entire file upload is complete. The third-party package that uses hutool is version 5.8.6.

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

Download Document

There is nothing to say about this, it is relatively simple, it is just a stream operation. The parameter passed in is the id of the saved file for file upload.

	@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("下载文件出错");
        }
    }

Study notes are for reference only!

Guess you like

Origin blog.csdn.net/weixin_51114236/article/details/131190578