gpt4 book ai didi

java - 如何使用 IO Codenameone 发布图片/图像

转载 作者:行者123 更新时间:2023-12-04 14:38:49 25 4
gpt4 key购买 nike

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

我正在使用的 Snippet 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);
}
});

最佳答案

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

只是如果我使用Write.flush function(),那么我的程序总是得到一个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);

?>

关于java - 如何使用 IO Codenameone 发布图片/图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10077470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com