Results 1 to 14 of 14
  1. #1
    dudejonne is offline Member
    Join Date
    Oct 2009
    Posts
    56
    Rep Power
    0

    Smile Upload an image.

    Okay, I got an applet from a friend working, the applet makes an Image called image. Is there a way to upload the image to my server like an image uploader like imageshack.us. Is this possible through Java? Or maybe can I send the Image image from Java to php?

  2. #2
    travishein's Avatar
    travishein is offline Senior Member
    Join Date
    Sep 2009
    Location
    Canada
    Posts
    684
    Rep Power
    6

    Default

    have you tried commons-httpclient, a Java HTTP client library, have your applet use this to invoke a POST to your server, and on the server side have a PHP handler receive the post body and extract the image and do what ever you do with it then.

  3. #3
    dudejonne is offline Member
    Join Date
    Oct 2009
    Posts
    56
    Rep Power
    0

    Smile

    Thanks, but I really don't know how to do that, could you help me out a little?

    I try to send an Image called image to php and then let php upload it to my server, just like imageshack.us does (so it returns a link and the people can view the image). But the only difference is I don't want to let the user browse his files, I just want to upload the image out of the Java applet.

  4. #4
    dudejonne is offline Member
    Join Date
    Oct 2009
    Posts
    56
    Rep Power
    0

    Default

    bump it up a little

  5. #5
    travishein's Avatar
    travishein is offline Senior Member
    Join Date
    Sep 2009
    Location
    Canada
    Posts
    684
    Rep Power
    6

    Default

    well, you have the sources for the applet ? as my suggestion to use the commons-httpclient to POST the image as the stream would require you to get into the applet. Also likely you would need to have some experience with building the applet again, e.g. Ant build script. And then to have the modified code .jar file deployed to your web server, but you mentioned applet was already working, so this part has been done before. I just keep forgetting to actually upload my modified jar file to the server and pull out hair wondering why the changes aren't working :). Andthe commons-httpclient will require adding their jar file and dependencies to the applet code base class:

    commons-httpclient.jar
    commons-codec.jar
    commons-logging.jar

    so, to use a custom HTTP POST, there are standards for multi-part form data content types, and RFC 2045 (MIME) encoding of the contents. but if you are using a custom PHP receiver on the server side, we might just as well stream the raw image data, and perhaps set a HTTP header for the file name we want the server to save it as.

    for example, once you have the Image object

    Java Code:
    /**
     *Created on Oct 29, 2009
     */
    
    import java.awt.image.BufferedImage;
    import java.awt.image.RenderedImage;
    import java.io.IOException;
    import java.io.PipedInputStream;
    import java.io.PipedOutputStream;
    
    import javax.imageio.ImageIO;
    
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpStatus;
    import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
    import org.apache.commons.httpclient.methods.PostMethod;
    
    
    public class ImageTest {
    
      public void theProgram() {
        
        // how ever you get your image object, like if its generated, or drawn.
        BufferedImage bimg = new BufferedImage(100, 100, BufferedImage.TYPE_3BYTE_BGR);
    
        // now that have the image, do the upload to the server.
        try {
          int statusCode =  uploadImage(bimg, "http://your.server.example.com/uploadImageHandler", "myImage.png");
          System.out.println("HTTP result code: " + statusCode); 
        } 
        catch (IOException ex) {
          // failed to upload 
        }
      }
    
      /**
       * uses commons-httpclient to send it to your server
       * @param bimg an image object to be uploaded
       * @param uploadUrl the HTTP url to our server-side handler to receive the image stream and do what ever with it.
       * @param targetFileName, the name we want this image saved as, such as in the uploads folder on the server.
       * @return
       */
      public int uploadImage(RenderedImage bimg, String uploadUrl, String targetFileName) throws IOException {
        int statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(uploadUrl);
        
        PipedOutputStream pout = new PipedOutputStream();
        PipedInputStream pin = new PipedInputStream(pout);
        
        // set any other request headers  
        postMethod.setRequestHeader("Content-Type", "image/png");
        
        // some header we invent to have the server able to save this stream to a file
        // the server-side handler will need to look for this.
        postMethod.setRequestHeader("Target-File-Name", targetFileName);
        postMethod.setRequestEntity(new InputStreamRequestEntity(pin));
        ImageIO.write(bimg, "png", pout);
       
        try {
          statusCode = httpClient.executeMethod(postMethod);
        }
        finally {
          postMethod.releaseConnection();
        }
        
        return statusCode;
      }
    }
    see also: Image IO


    I'ts been a while since I have used PHP on the server side, but you would need to have a handler to receive this post, look for the Target-File-Name HTTP header we stuffed into there, and then open the file for writing in some uploads folder or something, and then begin writing what ever it reads from the request into this file, until the end of the request.

    I don't like not setting the content length on the upload ahead of time, likely would be more robust, but unless we did some kind of write the image to a file on the applet side first, we can't know how large the rendered file would be until after its renderer.

    Hope thats helpful.

  6. #6
    dudejonne is offline Member
    Join Date
    Oct 2009
    Posts
    56
    Rep Power
    0

    Default

    ImageGrabber.java:14: package org.apache.commons.httpclient does not exist
    import org.apache.commons.httpclient.HttpClient;
    ^
    ImageGrabber.java:15: package org.apache.commons.httpclient does not exist
    import org.apache.commons.httpclient.HttpStatus;
    ^
    ImageGrabber.java:16: package org.apache.commons.httpclient.methods does not exi
    st
    import org.apache.commons.httpclient.methods.InputStreamR equestEntity;
    ^
    ImageGrabber.java:17: package org.apache.commons.httpclient.methods does not exi
    st
    import org.apache.commons.httpclient.methods.PostMethod;
    ^
    ImageGrabber.java:99: non-static method uploadImage(java.awt.image.RenderedImage
    ,java.lang.String,java.lang.String) cannot be referenced from a static context
    int statusCode = uploadImage(bimg, "C:/Documents and Settings/Jonneh/Bure
    aublad/Server/", "myImage.png");
    ^
    ImageGrabber.java:109: cannot find symbol
    symbol : variable bimgt
    location: class ImageGrabber
    new Viewer(bimgt);
    ^
    ImageGrabber.java:117: cannot find symbol
    symbol : variable HttpStatus
    location: class ImageGrabber
    int statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
    ^
    ImageGrabber.java:119: cannot find symbol
    symbol : class HttpClient
    location: class ImageGrabber
    HttpClient httpClient = new HttpClient();
    ^
    ImageGrabber.java:119: cannot find symbol
    symbol : class HttpClient
    location: class ImageGrabber
    HttpClient httpClient = new HttpClient();
    ^
    ImageGrabber.java:120: cannot find symbol
    symbol : class PostMethod
    location: class ImageGrabber
    PostMethod postMethod = new PostMethod(uploadUrl);
    ^
    ImageGrabber.java:120: cannot find symbol
    symbol : class PostMethod
    location: class ImageGrabber
    PostMethod postMethod = new PostMethod(uploadUrl);
    ^
    ImageGrabber.java:131: cannot find symbol
    symbol : class InputStreamRequestEntity
    location: class ImageGrabber
    postMethod.setRequestEntity(new InputStreamRequestEntity(pin));
    ^
    12 errors



    I did imported that stuf, should I download something extra or something to get it work? Also, I don't care about the file size or anything, I just want to store the image on my server or send it to php the easiest way. Thanks!

  7. #7
    dudejonne is offline Member
    Join Date
    Oct 2009
    Posts
    56
    Rep Power
    0

    Default

    I got another code working:

    try {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(bimg, "jpeg", baos);
    byte[] data = baos.toByteArray();
    URL u = new URL(here goes the url);
    HttpURLConnection out = (HttpURLConnection) u.openConnection();
    out.setRequestMethod("POST");
    out.setDoOutput(true);
    out.setDoInput(true);
    out.setRequestProperty("Content-Type", "image/png");
    out.setRequestProperty("Content-Length", Integer.toString(data.length));
    out.connect();
    OutputStream outs = out.getOutputStream();
    outs.write(data);
    outs.flush();
    outs.close();
    BufferedReader blah = new BufferedReader(new InputStreamReader(out.getInputStream()));
    String blahS;
    while((blahS = blah.readLine()) != null)
    System.out.println(blahS);
    } catch (Exception e) {
    e.printStackTrace();
    }

    But it gives this error:

    java.lang.ClassCastExeption: sun.net. www .protocol.file.FileURLConnection cannot be cast to java.net.HttpURLConnector

    Who knows how to fix it?

  8. #8
    travishein's Avatar
    travishein is offline Senior Member
    Join Date
    Sep 2009
    Location
    Canada
    Posts
    684
    Rep Power
    6

    Default

    I have been doing more thinking, if this is for an applet in a browser, perhaps the commons-httpclient way is a bit too heavyweight. so before i send you down a fox hole, see the discussion for a HttpUrlConnection apprach later on in this reply

    so. if we did want to still use the commons-httpclient, we need
    http://mirror.csclub.uwaterloo.ca/ap...client-3.1.zip
    I haven't used their current 4.0 yet, its pretty new. so i'd stick with the 3.1 for now.

    and its dependencies
    http://apache.mirror.iweb.ca/commons...-1.1.1-bin.zip
    http://apache.parentinginformed.com/...ec-1.4-bin.zip

    After you download these (3) pieces, each will contain a .jar file. we need to have that jar file used on the javac path, AND the applet runtime path. like if you use javac before on its own, now would need to javac -classpath commons-httpclient-3.1.jar:commons-logging-1.1.1.jar:commons-codec-1.4.jar

    or something, how ever your build environment finds and staples lib files into the compile path.

    and for deployment the applet tag needs to have these 3 jar files also added to its codebase path.


    The alternate approach using HttpUrlConnection works entirely with what's already bundled into the Java runtime, likely more convenient in your situation.

    A good general example of how this works can be found here

    and adapted their example,
    Java Code:
      /**
       * uses HttpUrlRequest to send it to your server
       * @param bimg an image object to be uploaded
       * @param uploadUrl the HTTP url to our server-side handler to receive the image stream and do what ever with it.
       * @param targetFileName, the name we want this image saved as, such as in the uploads folder on the server.
       * @return
       */
      public int uploadHttpUrlConnectionImage(RenderedImage bimg, String uploadUrl, String targetFileName) throws IOException {
        URL url;
        HttpURLConnection connection = null;  
        try {
          //Create connection
          url = new URL(uploadUrl);
          connection = (HttpURLConnection)url.openConnection();
          connection.setRequestMethod("POST");
          connection.setRequestProperty("Content-Type",  "image/png");
          connection.setRequestProperty("Target-File-Name", targetFileName);  
          
          
          connection.setUseCaches (false);
          connection.setDoInput(true);
          connection.setDoOutput(true);
    
          //Send request
          DataOutputStream wr = new DataOutputStream (
                      connection.getOutputStream ());
          
          ImageIO.write(bimg, "png", wr);
          wr.flush ();
          wr.close ();
    
          //Get Response  
          InputStream is = connection.getInputStream();
          BufferedReader rd = new BufferedReader(new InputStreamReader(is));
          String line;
          StringBuffer response = new StringBuffer(); 
          while((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
          }
          rd.close();
          
          return connection.getResponseCode();
    
        } catch (Exception e) {
    
          e.printStackTrace();
          return 500;
    
        } finally {
    
          if(connection != null) {
            connection.disconnect(); 
          }
        }
      }
    all this stuff is in the java.io package, so addding imports and compiling won't require those 3 jar files for the commons-httplclient thing.

  9. #9
    dudejonne is offline Member
    Join Date
    Oct 2009
    Posts
    56
    Rep Power
    0

    Default

    Thanks for your reply, I'll try it out later.
    But isn't it much simpler to do something like this:
    ImageIO.write(bufferedImage,"jpg",file);
    ?
    Wouldn't that store a buffered image as jpg on my server? If the applet was on my server too?

  10. #10
    dudejonne is offline Member
    Join Date
    Oct 2009
    Posts
    56
    Rep Power
    0

    Default

    Wait, now I have an applet that stores the image in the same folder as the applet. If I would upload the applet to my server, would it work too?

  11. #11
    travishein's Avatar
    travishein is offline Senior Member
    Join Date
    Sep 2009
    Location
    Canada
    Posts
    684
    Rep Power
    6

    Default

    Yea, i guess if you ran the applet in a web browser on the server, as a user with the write permission to a folder in the server, and if the saving to a local file is simpler and it does work, then in that case, it would get the file to the 'server' , since its the same file system. Usually applets need to be signed to allow them to have access to the local file system of the system that is running the browser client. but in your special case, that's also the server. I've been thinking in client/server land so long I never would have considered the simple special case of client is the server. :)

  12. #12
    dudejonne is offline Member
    Join Date
    Oct 2009
    Posts
    56
    Rep Power
    0

    Default

    Ok thnx, now I only need to get the applet working.

  13. #13
    dudejonne is offline Member
    Join Date
    Oct 2009
    Posts
    56
    Rep Power
    0

    Default

    okay bummer..
    ImageIO.write(bufferedImage,"jpg",file);
    isn't working.
    Anyone has a (simple? :) ) other solution?

  14. #14
    jfileupload is offline Member
    Join Date
    Mar 2008
    Posts
    10
    Rep Power
    0

    Default

    To avoid developing from scratch you could use JImageUpload. It's an applet allows to preview and upload images. It can upload overs HTTP or FTP. Also, if you need to scale image before upload then you can use JImageFilter add-on. You can try out them from jfileupload.com web site.

    Hope it could help.

Similar Threads

  1. :large file upload to server(chunk upload)
    By tommy_725 in forum Networking
    Replies: 0
    Last Post: 10-16-2009, 12:21 AM
  2. Upload image form client to fileserver
    By eratek in forum Networking
    Replies: 0
    Last Post: 03-20-2009, 11:13 AM
  3. How to upload image into server
    By vinodkonatala in forum Advanced Java
    Replies: 2
    Last Post: 10-15-2008, 12:10 PM
  4. Image upload applet 2.0
    By jfileupload in forum Java Software
    Replies: 0
    Last Post: 03-24-2008, 04:15 PM
  5. Replies: 0
    Last Post: 01-08-2008, 05:29 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •