Search This Blog

Friday, 30 November 2012

Upload and Download files- continued

In the previous post we saw how to process the MultipartFile parameter. We then wrote code to convert it into a byte array and use it in our code. This all works fine.
However we have seen custom editors that are capable of converting string parameters in HttpServletRequest into objects
that can be used directly in our code. So saving the headache of parsing the MultipartFile into a Byte stream or array would be a useful technique.
@RequestMapping(value = "upload.do", method = RequestMethod.POST)
public String uploadUserImage(
    @RequestParam(value = "image")  byte[] file)
    throws Exception {
    System.out.println("request received to upload image " + file);
    if (null != file) {
        final InputStream inputStream = new ByteArrayInputStream(file);
        System.out.println("uploading image wuth stream" + inputStream);
        this.imageManager.saveImage(inputStream);
        return "success";
    } else {
        throw new Exception("File not found ");
    }
}
    
@InitBinder
public void initBinder(final WebDataBinder binder) {
    binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
}
The initBinder will now ensure that the parameter is in the format we need. Similarly we have the StringMultipartFileEditor that converts multipartFile to Strings

The next step is to download the image. This is simple and can be achieved easily:
@RequestMapping(value = "download.do", method = RequestMethod.GET)
public void downloadUserImage(final HttpServletResponse response)
    throws IOException {
        final InputStream inStream = this.imageManager.getImage();
    response.setHeader("Pragma", "No-cache");
    // forces caches to submit the request to the origin server for
    // validation before releasing a cached copy, every time
    response.setDateHeader("Expires", this.createCacheExpiryDate()
        .getTime());
    response.setHeader("Cache-Control", "no-cache");
    response.setContentType("image/jpeg");

    final ServletOutputStream outStream = response.getOutputStream();
    final byte[] buffer = new byte[1024];
    int len = 0;
    while ((len = inStream.read(buffer)) > 0) {
        outStream.write(buffer, 0, len);
    }
    outStream.flush();
}

private Date createCacheExpiryDate() {
    final Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    // Addition of 24 hours from current time
    cal.add(Calendar.HOUR, 24);
    return cal.getTime();
}
The above code simply writes the file contents to the servlet's output stream. I have set some additional headers in the response to provide for browser caching and expiry as this is a GET call.

No comments:

Post a Comment