spring mvc上传、下载的实现

时间:2024-12-22 12:37:13

下载

//下载
@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>

文件下载参见 http://www.iteye.com/topic/1125784 这位老兄的这篇blog,这位老兄测试说存在问题,本人测试未发现有存在。