• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Unable to upload file using Swing and Servlets to Server

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Sheriff
Posts: 67746
173
Mac Mac OS X IntelliJ IDE jQuery TypeScript Java iOS
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Author
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You're making a POST but processing a GET.
 
KiranKumar Patel
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Is there anyone who can help me on this, its very urgent.
Thanks in advance.
 
David Newton
Author
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
http://www.java-tips.org/other-api-tips/httpclient/how-to-use-multipart-post-method-for-uploading.html
 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please, any one of you tell me that this code works fine.... If yes... nd if it needs some modifications please let me know...
 
Ranch Hand
Posts: 171
Spring Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
@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.
 
vishal bansode
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you all of you... I did it, but i ndifferent way..
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic