SpringMVC上传和下载

搭建SpringMvc开发环境web

导入包:spring

commons-fileupload-1.2.1.jarsession

commons-io-2.0.jarapp

配置文件上传解析器dom

 <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--上传文件的最大大小>
        <property name="maxUploadSize" value="17367648787"></property>
<!-- 上传文件的编码 --> 
       <property name="defaultEncoding" value="UTF-8"></property> 
   </bean>

上传页面post

<a href="down">下载图片</a>
    
    <form action="up" method="post" enctype="multipart/form-data">
        头像:<input type="file" name="uploadFile" />
        描述:<input type="text" name="desc" />
        <input type="submit" value="上传" />
    </form>编码

控制器方法.net

@Controller
public class TestUploadAndDownController {orm

    @RequestMapping("/down")
    public ResponseEntity<byte[]> down(HttpSession session) throws IOException{
        
        //获取下载文件的路径
        String realPath = session.getServletContext().getRealPath("img");
        String finalPath = realPath + File.separator + "2.jpg";
        InputStream is = new FileInputStream(finalPath);
        //available():获取输入流所读取的文件的最大字节数
        byte[] b = new byte[is.available()];
        is.read(b);
        //设置请求头
        HttpHeaders headers = new  HttpHeaders();
        headers.add("Content-Disposition", "attachment;filename=zzz.jpg");
        //设置响应状态
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(b, headers, statusCode);
        return entity;
    }
    
    @RequestMapping(value="/up", method=RequestMethod.POST)
    public String up(String desc, MultipartFile uploadFile, HttpSession session) throws IOException {
        //获取上传文件的名称
        String fileName = uploadFile.getOriginalFilename();
        String finalFileName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
        String path = session.getServletContext().getRealPath("photo") + File.separator + finalFileName;
        File file = new File(path);
        uploadFile.transferTo(file);
        return "success";
    }
    
    @RequestMapping(value="/up_old", method=RequestMethod.POST)
    public String up_old(String desc, MultipartFile uploadFile, HttpSession session) throws IOException {
        //获取上传文件的名称
        String fileName = uploadFile.getOriginalFilename();
        String path = session.getServletContext().getRealPath("photo") + File.separator + fileName;
        //获取输入流
        InputStream is = uploadFile.getInputStream();
        //获取输出流
        File file = new File(path);
        OutputStream os = new FileOutputStream(file);
        /*int i = 0;
        while((i = is.read()) != -1) {
            os.write(i);
        }*/
        
        /*int i = 0;
        byte[] b = new byte[1024];
        while((i = is.read(b)) != -1) {
            os.write(b, 0, i);
        }*/
        
        os.close();
        is.close();
        return "success";
    }
    
}图片