Uploading file to particular directory

You can configure the File Upload support in servlet specification 3.0 so that it uploads files to particular directory on your server.


package com.webspherenotes.j2ee6.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

/**
* Servlet implementation class HelloFileUploadAnnotationServlet
*/
@WebServlet("/hellofileupload")
@MultipartConfig(location="c:/temp/upload")
public class HelloFileUploadAnnotationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;


protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("Entering HelloFileUploadAnnotationServlet.doPost()");
response.setContentType("text/html");
response.getWriter().println("Hello from FileUploadServlet");
Collection fileParts = request.getParts();
Iterator filePartIt = fileParts.iterator();
while(filePartIt.hasNext()){
Part filePart = filePartIt.next();
System.out.println("File Name " + filePart.getName());
System.out.println("File Size " + filePart.getSize());

System.out.println("File Content ");
BufferedReader fileReader =
new BufferedReader(new InputStreamReader(filePart.getInputStream()));
String line = null;
while(( line = fileReader.readLine()) != null){
System.out.println(line);
}
}
System.out.println("Exiting HelloFileUploadAnnotationServlet.doPost()");
}

}


In my case i am setting value of location to c:/temp/upload and then i tried uploading couple of files and now i can see that every time i upload a file a .tmp file gets created in c:/temp/upload

2 comments: