aspose file tools*
The moose likes Servlets and the fly likes Unable to upload file using Swing and Servlets to Server Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Unable to upload file using Swing and Servlets to Server" Watch "Unable to upload file using Swing and Servlets to Server" New topic
Author

Unable to upload file using Swing and Servlets to Server

KiranKumar Patel
Greenhorn

Joined: Mar 08, 2010
Posts: 4
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
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60059
    
  65

Please be sure to use code tags when posting code to the forums. Unformatted code is extremely hard to read and many people that might be able to help you will just move along to posts that are easier to read. Please read this for more information.

You can go back and change your post to add code tags by clicking the button on your post.

[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

You're making a POST but processing a GET.
KiranKumar Patel
Greenhorn

Joined: Mar 08, 2010
Posts: 4
KiranKumar Patel wrote: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


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:



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
KiranKumar Patel
Greenhorn

Joined: Mar 08, 2010
Posts: 4
I am using doPost in my servlet, but still unable to get the file, please look into this it will be helpful.
KiranKumar Patel
Greenhorn

Joined: Mar 08, 2010
Posts: 4
Is there anyone who can help me on this, its very urgent.
Thanks in advance.
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

http://www.java-tips.org/other-api-tips/httpclient/how-to-use-multipart-post-method-for-uploading.html
vishal bansode
Greenhorn

Joined: Dec 08, 2010
Posts: 2
Please, any one of you tell me that this code works fine.... If yes... nd if it needs some modifications please let me know...
Kumaravadivel Subramani
Ranch Hand

Joined: Jul 05, 2008
Posts: 166

@Vishal - First try out the given example and if you have problem/doubt we would assist you. Don't expect the exact code that full fills your need.


No pain, No gain.
OCJP 1.6
vishal bansode
Greenhorn

Joined: Dec 08, 2010
Posts: 2
Thank you all of you... I did it, but i ndifferent way..
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Unable to upload file using Swing and Servlets to Server
 
Similar Threads
take in file from client machine
request.getParameter() returning null
problem with upload file using common file upload servlet
Uploading a file by parsing request
package javax.servlet.annotation does not exist