Uploading a file generated by Applet?

I create a java applet which is a kind of drawing program.
What I want is after a user finish his/her drawing I would like to save his/her work back to server as a JPEG file by catching this request with ASP.

At the server side I think I need something like
String name = request.getHeaderValue("Image-name");
//save rawData to the file with  
//name 'name'
byte[] rawData = request.getRawData();

The following is the core part of my applet for saving mechanism

FileOutputStream dataOut = new FileOutputStream("myJPG.jpg");
JpegEncoder myJPG = new JpegEncoder(iBackdrop,70,dataOut);

URL url;
URLConnection urlConn;
DataOutputStream printout;
// URL of ASP Page.
url = new URL (getCodeBase().toString() + "saveJPG.asp");
// URL connection channel.
urlConn = url.openConnection();
// Let the run-time system that we want input.        
urlConn.setDoInput (true);
// Let the RTS know that we want to do output.
urlConn.setDoOutput (true);
// No caching, we want the real thing.
urlConn.setUseCaches (false);
// Specify the content type.
urlConn.setRequestProperty("Content-Type", "image/jpeg");
urlConn.setRequestProperty("Image-name", "myJPG.jpg");
// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream());
String content = "fileName=" + URLEncoder.encode ("myJPG.jpg");
//and this is where the jpeg data is transfered?
printout.flush ();
printout.close ();

Thanks in advance
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

It's much easier to do with perl.  Are you sure that isn't an option available to you?

As I already mentioned (in the question you posted in the Javascript category) ASP is going to require a DLL to do the binary write to the file system.  If you don't have access to the server, odds are you won't be able to install the DLL anyway.  If you do have access to the server, install perl and do it the easy way (http://www.activestate.com).

If you decide you absolutely have to go with ASP, you have a couple of options.

1) you can reformat your java post so that it posts with multipart/form-data type encoding and install an ASP file upload control-- Software Artisan's FileUp http://www.softwareartisans.com/softartisans/saf.html, for example).  That way you don't have to write the custom DLL yourself and if you're lucky your ISP will actually allow the installation of FileUP.

Basically, you'd change a couple of lines within your java applet so that it posts as a standard file upload.

Your Content-Type would be of the multipart type separated by a boundary string:

  String boundary = "---------------------------7cf1f412178\n";

  urlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

Your content would then look like this:

  byte[] myJpegImage = getJpegAsArrayofBytes();

  String contentheader = "Content-Disposition: form-data; name=\"fileUpload\"; filename=\"myJpeg.jpg\"\n";
  contentheader += "Content-Type: image/jpeg\n\n";

  printout.writeBytes(boundary + "--");


2) you can post the data any way you want and handle it via ASP with the help of a custom DLL.  If you don't have control of the server, the chances that your ISP will allow you to install a custom DLL are slim to none.


If you find out that you can use perl, the following CGI will take care of the upload.

  use CGI::Carp ('fatalsToBrowser');
  $filename = $ENV{"QUERY_STRING"};
  $len = $ENV{"CONTENT_LENGTH"};
  read STDIN, $myContent, $len;
  open(OUTPUT, ">c:/path/to/myuploads/$filename") || die "Can't create file ($filename): $!\n";
  print OUTPUT $myContent;
  close OUTPUT;

# have to return a response otherwise java will complain.
  print "Content-type: text/html\n\n";
  print "Received $len bytes";
  close STDOUT;

Most of your java code would stay the same.  Change the URL so that it includes the filename within the querystring (that way you don't have to worry about separating it from the actual data of the Jpeg image).

url = new URL (getCodeBase().toString() + "saveJPG.pl?myJpeg.jpg");

Then change your java post so that it simply posts the byte array (leave the header info as it is-- since you're handling the post by hand, most of it doesn't really matter anyway):

byte[] content = getImageasJpegByteArray();
Optionally, you could use an ActiveX Upload control on the page..if all your users have v4.0+ browsers...

Or a third-party .dll to process the upload...such as www.aspsmart.com  (aspSmartUpload) www.aspupload.com by Persits... You can set file type and size limitations, truncating(if desired)..upload or download again from database or directory...pretty cool...

DaemonAuthor Commented:
Thanks for your comment clockwatcher.

I think your first suggestion is most suitable for me.
I downloaded "softartisans's" fileUp product.
Somehow, I am not able to upload my image that I created with my applet.
Could you take a moment to see what's wrong in my code?

This is the modified applet upload method.
you'd test that the variabe "bytearrayoutputstream" contain image file.

try {            
ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
JpegEncoder myJPG = new JpegEncoder(iBackdrop, 70, bytearrayoutputstream);
URL url;
URLConnection urlConn;
DataOutputStream printout;
url = new URL(getCodeBase().toString() + "formresp2.asp");
urlConn = url.openConnection(); urlConn.setDoInput(true);
String boundary="--------7cf1f412178\n";
urlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
printout = new DataOutputStream(urlConn.getOutputStream());
String contentheader = "Content-Disposition: form-data; name=\"fileUpload\"; filename=\"myJPG.jpg\"\n";
contentheader += "Content-Type: image/jpeg\n\n";
printout.writeBytes(boundary + "--");
} catch (Exception exception) {

The following is "formresp2.asp"

<% Set upl = Server.CreateObject("SoftArtisans.FileUp")
upl.Path = "c:\test\Up"
<% if upl.IsEmpty Then %>
The file that you uploaded was empty.
<% ElseIf upl.ContentDisposition <> "form-data" Then %>
Your upload did not succeed.<br>
<%Else %>
<P>The file was successfully transmitted by the user.</P>
on error resume next
if Err <> 0 Then %>
An error occurred when saving the file on the server.
<%      Else
      Response.Write("Upload saved successfully to " & upl.ServerName)
End If %>            
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

DaemonAuthor Commented:
I will increase my award point.
Sorry, java doesn't automatically "fix" the CRLF (like perl does) and the MIME standard calls for an extra "--" to demarcate the boundary.  

I wrote up and tested the following java application.  It works great.  I used a standard perl routine to catch the upload, but will try to download FileUp within the next day or so and give it a try.  If the standard perl routine recognizes it, I'm sure that FileUp won't have a problem.

Alter your java applet so that its post matches the following java application.

import java.net.*;
import java.io.*;

public class javaPostUpload {

public static void main(String args[]) {

    URL url;
    URLConnection urlConn;
    DataOutputStream printout;
    DataInputStream input;

    try {

    String boundary = "-----------------------------7cf2d017908";

    File myFile = new File("test.jpg");
    FileInputStream myFileStream = new FileInputStream(myFile);

    // URL of CGI-Bin script.
    url = new URL ("");

    urlConn = url.openConnection();
    urlConn.setDoInput (true);
    urlConn.setDoOutput (true);
    urlConn.setUseCaches (false);

    urlConn.setRequestProperty("Content-Type", "multipart/form-data, boundary=" + boundary);

    // Send POST output.
    printout = new DataOutputStream (urlConn.getOutputStream ());

    String contentHeader = "Content-Disposition: form-data; ame=\"fileName\";filename=\"test.jpg\"\r\n";
    contentHeader += "Content-Type: image/jpeg\r\n";
    contentHeader += "Content-Transfer-Encoding: binary\r\n\r\n";

    byte[] content;
    content = new byte[(int) myFile.length()];

    printout.writeBytes("--" + boundary + "\r\n");
    printout.writeBytes("\r\n--" + boundary + "--\r\n");

    printout.flush ();
    printout.close ();


    // Get response data.
    input = new DataInputStream (urlConn.getInputStream ());

    String str;
    while (null != ((str = input.readLine()))) {
       System.out.println (str);

    input.close ();

    } catch (Exception e) {

I've got a major project due Monday, so I don't know if I'll get a chance to get back to you until Tuesday.  I believe that if you match the post format, your applet and ASP page will work fine.  If you still need help by Tuesday, I'll post the full code for a working applet (rather than the application above) and an ASP file using FileUp to catch the upload.  But, I'm pretty sure you should be fine with the above sample.

Sorry about the first post missing a few \r's and a couple of dashes here and there.  I had to go back to the RFC's to catch it.
Looks like part of the post got cut-off.

The definition of contentHeader should have included an "n" ("name" instead of "ame") to define the name of the form field being posted.

String contentHeader = "Content-Disposition: form-data; name=\"fileName\"; filename=\"test.jpg\"\r\n";

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
DaemonAuthor Commented:
Thanks, clockwatcher.
I really appreciate your help.

Somehow I can compile and run your application without any error but it did not upload the file with my above "formresp2.asp" from softartisans's fileUp product.
I am very frustrated with this project and If you are too busy to guide me further. Can you give me url that I can study by myself regarding RFC stuffs.

DaemonAuthor Commented:
Actually, When I run your application I got these error messages.

java.io.IOException: Error writing to server at sun.net.www.protocol.http.HttpURLConnection.writeRequests(HttpURLConnection.java:213)

java.io.IOException: Error writing to server at sun.net.www.protocol.http.HttpURLConnection.writeRequests(HttpURLConnection.java:222)

java.io.IOException: Error writing to server at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:465)
at javaPostUpload.main(javaPostUpload.java Compiled code)
DaemonAuthor Commented:
Sorry, It was my jdk probelm.
Somehow I got corrected lib I think.
Your application is fine.
DaemonAuthor Commented:
Thanks clockwatcher,

I really appreciate your help.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.