如何在使用multipart / form数据上传图像时发送额外的变量

时间:2013-07-05 13:51:14

标签: java actionscript-3 flex servlets multipartform-data

请在这个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.");
        }

    }
}

2 个答案:

答案 0 :(得分:0)

你问题的flash部分怎么样:

标准AS3 FileReference不允许向多部分请求添加自定义参数,但您可以自己构建多部分请求并通过URLLoader发送。

以下是多部分请求创建的代码:

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

用法(使用fileUpload()方法代替标准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);

答案 1 :(得分:0)

Sotirios Delimanolis的建议帮助解决了这个问题,但我仍会尝试其他建议。

在AS3中

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

在Servlet中

String username = request.getHeader("username");