How do I post a picture/image using the IO Codenameone

狂风中的少年 提交于 2019-12-24 00:57:34

问题


Because codenameone can not use external libraries (HttpConnection) then I have to use the internal library / API provided Codenameone, it's just that I've managed to post the data to format text / string by using ConnectionRequest, I want to know is there any way to post the data in the form of an image with using ConnectionRequest? Thank you for your help

Snippet ConnectionRequest i'm using:

ConnectionRequest myrequest = new ConnectionRequest();
                                        myrequest.setUrl("http://www.xxxx.com/mobile/login/");
                                        myrequest.setPost(true);
                                        myrequest.addArgument("email", "info@xxx.net");
                                        myrequest.addArgument("password", "xxx");
                                        myrequest.setPriority(ConnectionRequest.PRIORITY_CRITICAL);
                                        NetworkManager.getInstance().addToQueue(myrequest);
                                        myrequest.addResponseListener(new ActionListener() {

                            @Override
                            public void actionPerformed(ActionEvent evt) {
                                NetworkEvent n = (NetworkEvent)evt;





                                // gets the data from the server as a byte array...
                                byte[] data = (byte[])n.getMetaData();
                                String response = new String(data);
                            }
                        });

回答1:


Sure you can just add the image data as an argument to the request but you will need to encode it. Alternatively you can override the method:

protected void buildRequestBody(OutputStream os) throws IOException

And write into the post output stream any arbitrary data you need.




回答2:


Thank you for your answer Shai, I see in the repository that has been added Codenameone MultipartRequest function (good job for Codenameone team)

It's just that if I use Write.flush function (), then the program I always get a Stream Closed Exception, but if I comment this command, the program I became normal again, following the code of which I edited slightly Codenameone suit my needs:

/**
* A multipart post request allows a developer to submit large binary data 
*  files to the server in a post request
*
* @author Shai Almog
*/
public class MultipartRequest extends ConnectionRequest {
private String boundary;
private Hashtable args = new Hashtable();
private Hashtable mimeTypes = new Hashtable();
private static final String CRLF = "\r\n"; 

protected void readResponse(InputStream input) throws IOException {
    // TODO Auto-generated method stub


        StringBuffer stringBuffer = new StringBuffer();
          int ch;
          while ((ch = input.read()) != -1) {
             stringBuffer.append((char) ch);
          }


        fireResponseListener(new NetworkEvent(this, stringBuffer.toString()));
}


/**
 * Initialize variables
 */
public MultipartRequest() {
    setPost(true);
    setWriteRequest(true);

    // Just generate some unique random value.
    boundary = Long.toString(System.currentTimeMillis(), 16); 

    // Line separator required by multipart/form-data.
    setContentType("multipart/form-data; boundary=" + boundary);
}

/**
 * Adds a binary argument to the arguments
 * @param name the name of the data
 * @param data the data as bytes
 * @param mimeType the mime type for the content
 */
public void addData(String name, byte[] data, String mimeType) {
    args.put(name, data);
    mimeTypes.put(name, mimeType);
}

/**
 * Adds a binary argument to the arguments, notice the input stream will be read only during submission
 * @param name the name of the data
 * @param data the data stream
 * @param mimeType the mime type for the content
 */
public void addData(String name, InputStream data, String mimeType) {
    args.put(name, data);
    mimeTypes.put(name, mimeType);
}

/**
 * @inheritDoc
 */
public void addArgument(String name, String value) {
    args.put(name, value);
}

/**
 * @inheritDoc
 */
protected void buildRequestBody(OutputStream os) throws IOException {
    Writer writer = null;
    writer = new OutputStreamWriter(os, "UTF-8"); 
    Enumeration e = args.keys();
    while(e.hasMoreElements()) {
        String key = (String)e.nextElement();
        Object value = args.get(key);

        writer.write("--" + boundary);
        writer.write(CRLF);
        if(value instanceof String) {
            writer.write("Content-Disposition: form-data; name=\"" + key + "\"");
            writer.write(CRLF);
            writer.write("Content-Type: text/plain; charset=UTF-8");
            writer.write(CRLF);
            writer.write(CRLF);
         //   writer.flush(); // always error if I use this??
            writer.write(Util.encodeBody((String)value));
            writer.write(CRLF); // always error if I use this??
           // writer.flush();
        } else {
            writer.write("Content-Disposition: form-data; name=\"" + key + "\"; filename=\"" + key +"\"");
            writer.write(CRLF);
            writer.write("Content-Type: ");
            writer.write((String)mimeTypes.get(key));
            writer.write(CRLF);
            writer.write("Content-Transfer-Encoding: binary");
            writer.write(CRLF);
            writer.write(CRLF);
            if(value instanceof InputStream) {
                InputStream i = (InputStream)value;
                byte[] buffer = new byte[8192];
                int s = i.read(buffer);
                while(s > -1) {
                    os.write(buffer, 0, s);
                    s = i.read(buffer);
                }
            } else {
                os.write((byte[])value);
            }
            writer.write(CRLF);
           // writer.flush();
        }
        writer.write(CRLF);
        //writer.flush();
    }

    writer.write("--" + boundary + "--");
    writer.write(CRLF);
    writer.close();
}

Examples of how to use :

 public class FormTest extends Form implements ActionListener{
private Button btnUpload;
private Button btnBrowse;
public  FormTest(){

    NetworkManager.getInstance().start();

    setLayout(new BoxLayout(BoxLayout.Y_AXIS));

    btnBrowse = new Button("Browse");
    btnUpload = new Button("Upload");

    addComponent(btnBrowse);
    addComponent(btnUpload);

    btnBrowse.addActionListener(this);
    btnUpload.addActionListener(this);



}
private MultipartRequest request;
public void actionPerformed(ActionEvent evt) {
    // TODO Auto-generated method stub
    if (evt.getSource().equals(btnBrowse)){
        //browse here

        btnBrowse.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent evt) {
                // TODO Auto-generated method stub
                Utility.pathfile = "";
                Utility.main.getFile();
                new Thread(new Runnable() {

                    public void run() {
                        // TODO Auto-generated method stub
                        while (Utility.pathfile.equals("")) {

                        }

                    }
                }).start();

            }
        });


    }

    if (evt.getSource().equals(btnUpload)){
        //upload here
        request = new MultipartRequest();
        request.setUrl("http://10.151.xx.xx/testuploadinfo.php");

        request.addArgument("Parameter1","Value1");
                    //add the data image
        request.addData("file", getTheImageByte("Your Url to Image here"),"image/png");

        request.setPriority(ConnectionRequest.PRIORITY_CRITICAL);
        request.addResponseListener(FormTest.this);
        NetworkManager.getInstance().addToQueue(request);
        //Dialog.show("Test","ok", "","");

    }
     if (evt instanceof NetworkEvent) {
         NetworkEvent ne = (NetworkEvent)evt;
         Dialog.show("Result:", ne.getMetaData().toString(), "","");

     }

}

private byte[] getTheImageByte(String url) {
    Bitmap bitmap = null, scaleBitmap = null;
    byte[] data = null;
    InputStream inputStream = null;
    FileConnection fileConnection = null;
    try {
        fileConnection = (FileConnection) Connector
                .open(url);
        if (fileConnection.exists()) {
            inputStream = fileConnection.openInputStream();
            data = new byte[(int) fileConnection.fileSize()];
            data = IOUtilities.streamToBytes(inputStream);



        }
    } catch (Exception e) {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
            if (fileConnection != null) {
                fileConnection.close();
            }
        } catch (Exception exp) {

        }

    }
    return data;// return the scale Bitmap not the original bitmap;
}

}

And simple PHP code :

 <?php



print_r($_FILES);
$new_image_name = "image.jpg";
move_uploaded_file($_FILES["file"]["tmp_name"], "sia/".$new_image_name);

?>



来源:https://stackoverflow.com/questions/10077470/how-do-i-post-a-picture-image-using-the-io-codenameone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!