JAVA项目中的IO流

一、将文件发返回给前端

Controller:

@ApiOperation(value = "IO流返回给前端")
@GetMapping("fileView")
public void fileView(@ApiParam(value = "文件路径", required = true) @RequestParam String fileUrl, HttpServletResponse response) {
    fileService.fileView(fileUrl, response);
}

Service:

    /**
     * 以IO流的形式返回给前端
     *
     * @param fileUrl  文件路径
     * @param response resp
     */
    public void fileView(String fileUrl, HttpServletResponse response) {
        // 读取文件名 例:yyds.jpg
        String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
        try (FileInputStream inputStream = new FileInputStream(fileUrl);
             OutputStream outputStream = response.getOutputStream()) {
            byte[] data = new byte[1024];
            // 全文件类型(传什么文件返回什么文件流)
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            response.setHeader("Accept-Ranges", "bytes");
            int read;
            while ((read = inputStream.read(data)) != -1) {
                outputStream.write(data, 0, read);
            }
            // 将缓存区数据进行输出
            outputStream.flush();
        } catch (IOException e) {
            log.error("失败", e);
            throw new Exception("exception");
        }
    }

二、将前端的文件信息返回后端处理

 pring框架在spring-web包中对文件上传进行了封装,大大简化了服务端代码,我们只需要在Controller的方法中声明一个MultipartFile类型的参数即可接收上传的文件,例如:

先写好一个配置在application.yml,以备使用

files:
  upload:
    path: F:/后台管理系统/files/

 Controller

@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {
	//文件磁盘路径
    @Value("${files.upload.path}")
    private String fileUploadPath;

    @PostMapping("/upload")
    public Result upload(@RequestParam MultipartFile file) throws IOException {
        //获取文件原始名称
        String originalFilename = file.getOriginalFilename();
        //获取文件的类型
        String type = FileUtil.extName(originalFilename);
        log.info("文件类型是:" + type);
        //获取文件大小
        long size = file.getSize();

        //获取文件
        File uploadParentFile = new File(fileUploadPath);
        //判断文件目录是否存在
        if(!uploadParentFile.exists()) {
            //如果不存在就创建文件夹
            uploadParentFile.mkdirs();
        }
        //定义一个文件唯一标识码(UUID)
        String uuid = UUID.randomUUID().toString();

        File uploadFile = new File(fileUploadPath + uuid + StrUtil.DOT + type);
        //将临时文件转存到指定磁盘位置
        file.transferTo(uploadFile);
            
        return Result.success("");
    }
}

即可完成 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值