0

请我在这个 AS3 和 Java 代码方面需要你的帮助。该程序旨在将图片从 flex 应用程序上传到远程服务器。该代码运行良好,但我需要添加一些东西,我正在寻找一种与图像一起发送和额外参数的方法。假设我想将上传图片的人的用户名与图片一起发送。请问如何使用 AS3 从客户端发送它以及如何在 servlet 上接收数据。

这是AS3代码

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);
                    }

这是Servlet上的代码。请注意多行注释。提前致谢。

// 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.");
        }

    }
}
4

2 回答 2

0

你的问题的闪光部分怎么样:

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);
于 2013-07-05T14:37:44.760 回答
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");
于 2013-07-07T12:50:56.030 回答