Codenameone上传图片

时间:2015-12-14 11:37:19

标签: php codenameone

我正在尝试使用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。请协助

2 个答案:

答案 0 :(得分:4)

您需要在第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);
}

在旁注中,始终在try和catch中运行Capture。如果用户取消图像捕获或发生其他事情,则会抛出异常。

答案 1 :(得分:0)

我的存储图像解决方案

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