美文网首页
RESTful文件上传与下载

RESTful文件上传与下载

作者: Burning_6c93 | 来源:发表于2019-02-05 15:40 被阅读0次

    文件上传

        @Test
        public void whenUploadSuccess() {
            try {
                String file = mockMvc.perform(MockMvcRequestBuilders.fileUpload("/file")
                        .file(new MockMultipartFile("file", "test.txt",
                                "multipart/form-data", "hello upload".getBytes("UTF-8"))))
                        .andExpect(MockMvcResultMatchers.status().isOk())
                        .andReturn().getResponse().getContentAsString();
                log.info("file:{}",file);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        @PostMapping
        public FileInfo upload(MultipartFile file) {
            log.info(file.getName());
            log.info(file.getOriginalFilename());
            log.info(String.valueOf(file.getSize()));
            File localFile = new File(folder, new Date().getTime() + ".txt");
            try {
                file.transferTo(localFile);
                return new FileInfo(localFile.getAbsolutePath());
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
    
        }
    

    文件下载

        @GetMapping("/{id}")
        public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) {
            try (InputStream ips = new FileInputStream(new File(folder, id + ".txt"));
                 OutputStream ops = response.getOutputStream();) {
                response.setContentType("application/x-download");
                response.setHeader("Content-Disposition", "attachment;filename=test.txt");
                IOUtils.copy(ips, ops);
                ops.flush();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    

    相关文章

      网友评论

          本文标题:RESTful文件上传与下载

          本文链接:https://www.haomeiwen.com/subject/defvsqtx.html