Hello Friends,
I have a Swing class which uses a FileChooser to select a file, I want that File to be sent to the
Servlet, this servlet will upload the file to the server. I have used the commons file upload apache package for this. I am able to upload file using an HTML form and Servlet.
Below is my Swing program: FileUpload.java
public void actionPerformed(ActionEvent e) {
if (e.getSource() == jbttn2Upload){
//** Check if file is selected
if (jtxt2.getText().equals(""))
{
JOptionPane.showMessageDialog(null, "Please select a file to upload","ICCLauncher",1);
System.out.println("In first if of upload");
}
else
{
//**If file is selected then proceed
try {
String url =
"http://localhost:8081/examples/servlet/CommonsFileUploadServlet";
File srcfile = fc.getSelectedFile();
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod(url);
System.out.println("file exists = "+srcfile.exists());
postMethod.addRequestHeader("Content-type","multipart/form-data;boundary="+srcfile.length());
postMethod.addRequestHeader("content-disposition","form-data; name="+srcfile.getName());
System.out.println(srcfile.getName());
postMethod.setRequestEntity(new FileRequestEntity(srcfile,
"multipart/form-data;boundary=----7d41e5b3904fc---"));
postMethod.setRequestHeader("Content-type",
"multipart/form-data;boundary=--7e5c--");
int statusCode1 = client.executeMethod(postMethod);
if (statusCode1 == HttpStatus.SC_OK) {
System.out.println("The Post method is implemented");
// still consume the response body
System.out.println(postMethod.getResponseBodyAsString());
}
System.out.println("status >>> "+statusCode1);
System.out.println("statusLine1>>>" + postMethod.getStatusLine());
System.out.println("statusLine3>>>" + postMethod.getParameters());
postMethod.releaseConnection();
} catch (MalformedURLException ex) { // new URL() failed
System.out.println("In first catch of upload");
} catch (IOException ax) { // openConnection() failed
System.out.println("In second catch of upload");
}
}
}
}
In the above program we have used System.out.println, just to trace the execution path of the program. After we run the above program in Myeclipse, we get the below output in the console:
file exists = true
Practice.txt [this is the file selected for upload from Filechooser]
POST
The Post method is implemented
//****this output is received from postMethod.getResponseBodyAsString()
<h1>Servlet File</h1>
org.apache.tomcat.util.http.NamesEnumerator@1551b0
POST
/examples
java.util.Hashtable$EmptyEnumerator@f01771
Is Multipart= true
***** items = []
//*****
status >>> 200
statusLine1>>>HTTP/1.1 200 OK
statusLine3>>>[Lorg.apache.commons.httpclient.NameValuePair;@d55986
In first ELSE of upload
Below is the servlet program:
import java.io.File;
import java.io.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class CommonsFileUploadServlet extends HttpServlet {
private static final String TMP_DIR_PATH = "c:\\tmp";
private File tmpDir;
private static final String DESTINATION_DIR_PATH ="/files";
private File destinationDir;
public void init(ServletConfig config) throws ServletException {
super.init(config);
tmpDir = new File(TMP_DIR_PATH);
if(!tmpDir.isDirectory()) {
throw new ServletException(TMP_DIR_PATH + " is not a directory");
}
String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
destinationDir = new File(realPath);
if(!destinationDir.isDirectory()) {
throw new ServletException(DESTINATION_DIR_PATH+" is not a directory");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/plain");
out.println("<h1>Servlet File</h1>");
out.println(request.getHeaderNames());
out.println(request.getMethod());
out.println(request.getContextPath());
out.println(request.getParameterNames());
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
out.println("Is Multipart= "+isMultipart);
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory ();
/*
*Set the size threshold, above which content will be stored on disk.
*/
fileItemFactory.setSizeThreshold(1*1024*1024); //1 MB
/*
* Set the temporary directory to store the uploaded files of size above threshold.
*/
fileItemFactory.setRepository(tmpDir);
ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
try {
PrintWriter out1 = response.getWriter();
response.setContentType("text/plain");
/*
* Parse the request
*/
List items = uploadHandler.parseRequest(request);
Iterator itr = items.iterator();
out1.println("***** items = " +items);
while(itr.hasNext()) {
FileItem item = (FileItem) itr.next();
/*
* Handle Form Fields.
*/
if(item.isFormField()) {
out.println("File Name = "+item.getFieldName()+", Value = "+item.getString());
} else {
//Handle Uploaded files.
out.println("Field Name = "+item.getFieldName()+
", File Name = "+item.getName()+
", Content type = "+item.getContentType()+
", File Size = "+item.getSize());
// Write file to the ultimate location.
File file = new File(destinationDir,item.getName());
item.write(file);
out.close();
}
}
}catch(FileUploadException ex) {
out.println(ex.getMessage());
} catch(Exception ex) {
log("Error encountered while uploading file",ex);
}
}
}
I am unable to upload file, I am using above 2 programs, as per the console this statement code [List items = uploadHandler.parseRequest(request);] returns an empty item list is this because that the file is not received by the Servlet, Please help me on this, its very important, any help will be greatly appreciated.
Thanks,
Kiran Patel