【问题标题】:How do I post a picture/image using the IO Codenameone如何使用 IO Codenameone 发布图片/图像
【发布时间】:2016-11-18 18:40:12
【问题描述】:

因为codenameone不能使用外部库(HttpConnection)所以我必须使用内部库/API提供的Codenameone,只是我已经设法通过使用ConnectionRequest将数据发布为格式化文本/字符串,我想知道有没有办法使用 ConnectionRequest 以图像的形式发布数据?谢谢你的帮助

我正在使用的片段连接请求:

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

【问题讨论】:

    标签: java image post lwuit codenameone


    【解决方案1】:

    感谢您的回答 Shai,我在存储库中看到已添加 Codenameone MultipartRequest 功能(Codenameone 团队做得很好)

    只是如果我使用Write.flush函数(),那么程序我总是得到一个Stream Closed Exception,但是如果我注释这个命令,我的程序又恢复正常了,按照我编辑的代码稍微Codenameone满足我的需要:

    /**
    * 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();
    }
    

    使用示例:

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

    }

    还有简单的 PHP 代码:

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

    ?>

    【讨论】:

      【解决方案2】:

      当然,您可以将图像数据作为参数添加到请求中,但您需要对其进行编码。或者,您可以覆盖该方法:

      protected void buildRequestBody(OutputStream os) throws IOException
      

      并将所需的任意数据写入后输出流。

      【讨论】:

      • 能否请您给我上传图片的基本代码以及代号中的示例?
      • 我们有 MultipartRequest 并且它发送一个标准的多部分提交。在这种情况下,接受多部分内容的标准 Java servlet 应该可以正常工作。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-25
      • 2021-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      • 2017-10-23
      相关资源
      最近更新 更多