Codenameone上传图片

Codenameone uploading an image

我正在尝试使用 codenameone

将图像从应用程序上传到远程主机
MultipartRequest cr = new MultipartRequest();
String  filePath = Capture.capturePhoto(Display.getInstance().getDisplayWidth(), -1);
cr.setUrl(url);
cr.setPost(true);
String mime="image/jpeg";
cr.addData("img", filePath, mime);

InfiniteProgress prog = new InfiniteProgress();
Dialog dlg = prog.showInifiniteBlocking();
cr.setDisposeOnCompletion(dlg);
NetworkManager.getInstance().addToQueueAndWait(cr);

PHP 页面上,我在图像名称上得到一个 null。请协助

您需要设置文件名并将第 6 行的 "img" 更改为 "file":

MultipartRequest cr = new MultipartRequest();
String  filePath = Capture.capturePhoto(Display.getInstance().getDisplayWidth(), -1);
cr.setUrl(url);
cr.setPost(true);
String mime="image/jpeg";
cr.addData("file", filePath, mime);
cr.setFilename("file", "MyImage.jpg");//any unique name you want

InfiniteProgress prog = new InfiniteProgress();
Dialog dlg = prog.showInifiniteBlocking();
cr.setDisposeOnCompletion(dlg);
NetworkManager.getInstance().addToQueueAndWait(cr);

然后在php这边,调用文件名:

$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);

if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/pjpeg") || ($_FILES["file"]["type"] == "image/x-png") || ($_FILES["file"]["type"] == "image/png")) && ($_FILES["file"]["size"] < 5000000) && in_array($extension, $allowedExts)) {
    if ($_FILES["file"]["error"] > 0) {
        $named_array = array("Response" => array(array("Status" => "error")));
        echo json_encode($named_array);
    } else {
        move_uploaded_file($_FILES["file"]["tmp_name"], "FolderPath/" . $_FILES["file"]["name"]);

        $Path = $_FILES["file"]["name"];
        $named_array = array("Response" => array(array("Status" => "ok")));
        echo json_encode($named_array);
    }
} else {
    $named_array = array("Response" => array(array("Status" => "invalid")));
    echo json_encode($named_array);
}

附带说明,总是运行在尝试和捕捉中捕获。如果用户取消图像捕获或发生其他情况,将抛出异常。

我的存储图像解决方案

String fileName = "";
MultipartRequest multipartRequest = new MultipartRequest();
InfiniteProgress progressIndicator = new InfiniteProgress();
Dialog dialog = progressIndicator.showInifiniteBlocking();
InputStream is = Storage.getInstance().createInputStream(fileName);
multipartRequest.setUrl(SERVICEURL + "upload");
multipartRequest.setPost(true);
multipartRequest.setFailSilently(true);
multipartRequest.setTimeout(30000);
multipartRequest.addData("file", is, Storage.getInstance().entrySize(fileName), "image/jpg");
multipartRequest.setFilename("file", fileName);
NetworkManager.getInstance().addToQueueAndWait(multipartRequest);
multipartRequest.setDisposeOnCompletion(dialog);