spring mvc上傳、下載的實現

下載

複製代碼
//下載
    @RequestMapping(value="/download")
    public ResponseEntity<byte[]> download() throws IOException{
        String fileName = "test.txt";
        File downloadFile = new File("D:/test.txt");
        
        HttpHeaders headers = new HttpHeaders();  
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);  
        headers.setContentDispositionFormData("attachment", fileName);  
        
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(downloadFile),  
                                          headers, HttpStatus.CREATED);  
    }
複製代碼

上傳

複製代碼
@RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(@RequestParam("name") String name,
            @RequestParam("file") MultipartFile file,RedirectAttributes attributes){
        System.out.println("param:"+name);
        if(!file.isEmpty()){
            System.out.println("upload ok");
        }
        
        attributes.addAttribute("name", "upload success");
        return "redirect:/login.jsp";
    }
複製代碼

spring配置文件

<!-- 文件上傳解析器 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- one of the properties available; the maximum file size in bytes -->
        <property name="maxUploadSize" value="-1"/>
    </bean>
發佈了40 篇原創文章 · 獲贊 4 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章