栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java编写简单的文件上传与下载

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java编写简单的文件上传与下载

两个接口由于时间关系,都是按照最简单的方式编写,还有很多问题,但文件的处理方式没有问题。

1.文件上传

文件上传,使用表单方式上传 MultipartFile multipartFile 参数 后端就收到文件,存储到指定的文件夹下,并进行重命名

 @RequestMapping(value = "/uploadFile",method = RequestMethod.POST)
    public void uploadFileTest(MultipartFile multipartFile) throws  Exception{
        String orgFile = multipartFile.getOriginalFilename();
        String fileName = UUID.randomUUID().toString().replace("-","")+orgFile.substring(orgFile.lastIndexOf("."));
        Path path = Paths.get("D:/resFile/".concat(fileName));
        if (Files.notExists(path)){
            path = Files.createFile(path);
        }
        Long s = Files.copy(multipartFile.getInputStream(),path, StandardCopyOption.REPLACE_EXISTING);
        System.out.println("文件大小为:"+s);
    }

2.文件下载

文件下载,浏览器传递文件名或者路径到后台接口,后台根据路径将文件下载。

    @GetMapping(value = "/downFile")
    public void downFileTest(
            @RequestParam(name = "fileName")String fileName, HttpServletResponse response) throws Exception{
        String filePath = "D:/resFile/";
        String contentType = Files.probeContentType(Paths.get(filePath));
        response.setHeader("Content-Type", contentType);
        response.setHeader("Content-Disposition", "attachment;filename="
                + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
        File file = new File(filePath+fileName);
        FileChannel inChannel = null;
        WritableByteChannel outChannel = null;
        outChannel = Channels.newChannel(response.getOutputStream());
        inChannel = new FileInputStream(file).getChannel();
        inChannel.transferTo(0,inChannel.size(),outChannel);
        inChannel.close();
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/872490.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号