0

I have written a servlet using servlet3.0 for uploading the file and it uploads the file very well. But I want to save the file in the server in the format it is uploaded by the client.

        Part filePart = request.getPart("chosenFile");

        String filename = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()).toString();
        System.out.println(filePart.getContentType().split("/")[1]);

        InputStream inputStream =null;
        OutputStream outputStream =null;

        File fileSaveDirectory = new File(UPLOAD_DIR);
        if(!fileSaveDirectory.exists()){
            fileSaveDirectory.mkdir();
        }

        String content_path = UPLOAD_DIR+File.separator+filename;//earlier
        //here I was appending the string ".pdf" to every file
        //but now I want the file type to be the uploaded file type.
        //say if user uploads in .jpeg or any other.

        System.out.println("Content Path : "+content_path);

        outputStream = new FileOutputStream(new File(content_path));
        inputStream = filePart.getInputStream();
        int read=0;

        while((read=inputStream.read())!=-1){
            outputStream.write(read);
        }

        if(outputStream!=null)
            outputStream.close();
        if(inputStream !=null)
            inputStream.close();

How to keep the file type , the type of uploaded file. Please help !!!

1 Answers1

1

See @ http://docs.oracle.com/javaee/6/tutorial/doc/glraq.html:

private String getFileName(final Part part) {
    final String partHeader = part.getHeader("content-disposition");
    LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
    for (String content : part.getHeader("content-disposition").split(";")) {
        if (content.trim().startsWith("filename")) {
            return content.substring(
                    content.indexOf('=') + 1).trim().replace("\"", "");
        }
    }
    return null;
}

So, when your (file upload) request is setup well/normal, the (http) header content-disposition will contain (among others, separated by ;) a filename attribute, which you can use (in the whole or) to extract the file suffix.

xerx593
  • 12,237
  • 5
  • 33
  • 64