0

please i need your help in this AS3 and Java Code. The program is meant to upload a picture from a flex app to a remote server. The code works well, but i need to add something, i am looking for a way to send and extra parameter along with the image. Lets say i want to send the username of the person uploading the image along with the image. Please how do i send it from the client side using AS3 and how do i receive the data on the servlet.

Here is AS3 code

private var fileRef:FileReference = new FileReference();
private var servletTarget:URLRequest = new URLRequest(urlpath+"Comeboard/UploadImage");

                    private function fileBrowse():void
                    {
                      fileRef.addEventListener(Event.SELECT, onSelect);
                      fileRef.addEventListener(ProgressEvent.PROGRESS,progressHandler);
                            //just a label
                            uploadStatus.text = "Browsing the File System";
                            //a text field
                            fileLocation.text = "";
                            fileRef.browse();
                    }
                    private function onSelect(event:Event):void
                    {
                            uploadStatus.text = "File selected";
                            fileLocation.text = fileRef.name;
                    }
                    private function progressHandler(event:ProgressEvent):void
                    {

                       uploadStatus.text = "The file is " + percentLoaded + "% loaded";
                    }
                    private function fileUpload():void
                    {

                            //assuming this is the data i want to send
                            var data:String = "webdezzi";
                            uploadStatus.text = "Uploading....";
                            var menuURLVars:URLVariables = new URLVariables();
                            servletTarget.method = URLRequestMethod.POST;
                            fileRef.upload(servletTarget);
                    }

Here is the Code on the Servlet. Please pay attention to the multi line comment. Thanks in advance.

// Import required java libraries
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadImage extends HttpServlet {

  String boardname = null;
  private boolean isMultipart;
  private String filePath;
  private int maxFileSize = 1000 * 1024;
  private int maxMemSize = 4 * 1024;
  private File file ;
  private static final long serialVersionUID = 1L;

  public void init( )
  {
     // Get the file location where it would be stored.
    filePath =
         getServletContext().getRealPath("/");
  }
  public void doPost(HttpServletRequest request,
           HttpServletResponse response)
          throws ServletException, java.io.IOException
 {

  // Check that we have a file upload request
  isMultipart = ServletFileUpload.isMultipartContent(request);
  response.setContentType("text/html");
  java.io.PrintWriter out = response.getWriter( );
  if( !isMultipart )
  {
     out.println("<html>");
     out.println("<head>");
     out.println("<title>Servlet upload</title>");
     out.println("</head>");
     out.println("<body>");
     out.println("<p>No file uploaded</p>");
     out.println("</body>");
     out.println("</html>");
     return;
  }

  DiskFileItemFactory factory = new DiskFileItemFactory();
  // maximum size that will be stored in memory
  factory.setSizeThreshold(maxMemSize);



  // Create a new file upload handler
  ServletFileUpload upload = new ServletFileUpload(factory);

  // maximum file size to be uploaded.
  upload.setSizeMax( maxFileSize );

  try{
  // Parse the request to get file items.
  List fileItems = upload.parseRequest(request);

  // Process the uploaded file items
  Iterator i = fileItems.iterator();

  out.println("<html>");
  out.println("<head>");
  out.println("<title>Servlet upload</title>");
  out.println("</head>");
  out.println("<body>");
  while ( i.hasNext () )
  {
     FileItem fi = (FileItem)i.next();
     System.out.println("kkkkkkkk"+fi.getFieldName());
     if (fi.isFormField())
     {

       /*****************************************************
       *  i beleive this is where i am supposed to
       *    process the data i receive.
       *    i might be wrong though,                                                *
    ******************************************************/
         processFormField(fi);
     }
     if ( !fi.isFormField () )
     {


         processUploadedFile(fi);
     }
  }
  out.println("</body>");
  out.println("</html>");
 }
  catch(Exception ex)
  {
   out.println(ex.getMessage());
  }
}
 public void doGet(HttpServletRequest request,
                   HttpServletResponse response)
    throws ServletException, java.io.IOException
 {
  throw new ServletException("GET method used with " +
         getClass( ).getName( )+": POST method required.");
 }

    private void processFormField(FileItem item)
    {
        String name = item.getFieldName();
        String value = item.getString();
        System.out.println("Item name: " + name + " ; value: " + value);
    }

    private void processUploadedFile(FileItem item) throws Exception
    {
        String fieldName = item.getFieldName();
        String fileName = item.getName();

        String contentType = item.getContentType();
        boolean isInMemory = item.isInMemory();
        long sizeInBytes = item.getSize();

        boolean writeToFile = true;
        if (sizeInBytes > (5 * 1024 * 1024))
        {
            writeToFile = false;
        }
        // Process a file upload
        if (writeToFile)
        {
            //File uploadedFile = new File(filePath + fileName);
             File uploadedFile = new File(filePath + boardname);
            if (!uploadedFile.exists())
            {
             uploadedFile.createNewFile();

            }
        item.write(uploadedFile);
        }
        else
        {
             System.out.println("Trying to write a large file.");
        }

    }
}

3 Answers3

0

What about flash part of your question:

Standard AS3 FileReference doesn't allow to add custom parameters to the multipart request, but you can construct the multipart request yourself and send it via URLLoader.

Here is the code for multipart request creation:

private static const BOUNDARY:String = "boundary";

public static function createMultiPartRequest(url:String, bytes:ByteArray, fileProp:String="file1", fileName:String="file1.png", params:Object=null):URLRequest
{
    var request:URLRequest = new URLRequest(url);

    var header1:String = "\r\n--" + BOUNDARY + "\r\n" + 
        "Content-Disposition: form-data; name=\""+fileProp+"\"; filename=\""+fileName+"\"\r\n" + 
        "Content-Type: image/png\r\n" + "\r\n";
    var headerBytes1:ByteArray = new ByteArray();
    headerBytes1.writeMultiByte(header1, "ascii");
    var postData:ByteArray = new ByteArray();
    postData.writeBytes(headerBytes1, 0, headerBytes1.length);

    if(bytes)
        postData.writeBytes(bytes, 0, bytes.length);

    if (!params)
        params = {};
    if (!params.Upload)
        params.Upload = "Submit Query";
    for (var prop:String in params) {
        var header:String = "--" + BOUNDARY + "\r\n" + "Content-Disposition: form-data; name=\""+prop+"\"\r\n" + "\r\n" + params[prop]+"\r\n" + "--" + BOUNDARY + "--";
        var headerBytes:ByteArray = new ByteArray();
        headerBytes.writeMultiByte(header, "ascii");
        postData.writeBytes(headerBytes, 0, headerBytes.length);
    }
    request.data = postData;
    request.method = URLRequestMethod.POST;
    request.contentType = "multipart/form-data; boundary=" + BOUNDARY;

    return request;
}

Usage (in your fileUpload() method instead of standard fileRef.upload()):

    var image:ByteArray = fileRef.data;
    var request:URLRequest = createMultiPartRequest("test.com", image, "file1", "file1.png", {param1:value1});
    var loader:URLLoader = new URLLoader();
    loader.load(request);
fsbmain
  • 5,267
  • 2
  • 16
  • 23
0

Sotirios Delimanolis advice helped solve the problem, but i would still try other suggestions on this.

In the AS3

    var header:URLRequestHeader = new URLRequestHeader("username", username);
        servletTarget.requestHeaders.push(header);

In the Servlet

String username = request.getHeader("username");
  • Actually, this is not possible as you can't use URLRequestHeader with FileReference. Instead, use URLVariables to send additional parameters to the upload script. – Manish May 01 '22 at 21:13
0

The selected answer is not correct. According to the AS3 reference

Not all methods that accept URLRequest parameters support the requestHeaders property, consult the documentation for the method you are calling. For example, the FileReference.upload() and FileReference.download() methods do not support the URLRequest.requestHeaders property.

Refer Using the FileReference class to understand how to send additional parameters.

You can pass additional variables to the upload script using either the POST or GET request method. To send additional POST variables to your upload script, you can use the following code:

    fileRef:FileReference = new FileReference();
    fileRef.addEventListener(Event.SELECT, selectHandler);
    fileRef.addEventListener(Event.COMPLETE, completeHandler);
    fileRef.browse();

    function selectHandler(event:Event):void {
       var params:URLVariables = new URLVariables();
       params.date = new Date();
       params.ssid = "94103-1394-2345";
       var request:URLRequest = new URLRequest("http://www.yourdomain.com/FileReferenceUpload/fileupload.cfm");
       request.method = URLRequestMethod.POST;
       request.data = params;
       fileRef.upload(request, "Custom1");
   }

   function completeHandler(event:Event):void {
      trace("uploaded");
   }

Hope this helps someone in the future.

Manish
  • 87
  • 7