【发布时间】:2017-09-06 12:29:18
【问题描述】:
好的,我不认为这是 cn1 问题,但我已经没有其他选择了。我有一个应用程序,我一直在使用 Capture.capturePhoto 让用户能够使用他们的设备拍摄照片并将其上传到我的服务器。几个月来一直工作得很好。我被要求添加从手机照片库上传照片的功能,我认为这很简单,但是在弄清楚如何缩小图像并将其存储在存储中之后,我现在只发送 0 就很难过字节到我的服务器。
我知道这不是我的服务器,它没有改变,仍然可以从各种来源上传文件,包括用 cn1 应用程序中的照片捕获的文件。
这是上传照片的代码
private void uploadImage(String filename, String name) throws IOException {
String ext = filename.substring(filename.lastIndexOf('.') + 1).toLowerCase();
if (ext.equals("jpg") || ext.equals("jpeg") || ext.equals("pjpeg") || ext.equals("png")) {
MultipartRequest request = new MultipartRequest() {
Hashtable h;
@Override
protected void readResponse(InputStream input) throws IOException {
JSONParser p = new JSONParser();
h = p.parse(new InputStreamReader(input));
super.readResponse(input);
}
@Override
protected void postResponse() {
List<Map<String, Object>> media = (List<Map<String, Object>>)h.get("media");
Dialog.show("Photo Uploaded", media.size() + " photo(s) uploaded and available to send.", "OK", null);
}
};
request.setUrl(MyApplication.IMGSERVER);
request.setPost(true);
request.addData(name, filename, "image/" + ext);
request.addRequestHeader("X-Dart-Token", token);
NetworkManager.getInstance().addToQueue(request);
} else {
Dialog.show("Invalid Photo Format", "The photo format (" + ext+ ") is not supported. Try with jpg or png.", "OK", null);
}
}
这是从图库中获取和缩放照片的相关代码部分
Display.getInstance().openGallery(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
if (actionEvent != null && actionEvent.getSource() != null) {
String filepath = (String)actionEvent.getSource();
if (filepath != null) {
// scale down the image
String filename = "tempfile.png";
boolean success = false;
if (Storage.isInitialized()) {
try {
OutputStream out = Storage.getInstance().createOutputStream(filename);
ImageIO.getImageIO().save(filepath, out, ImageIO.FORMAT_PNG, 500, -1, 1);
out.close();
success = true;
} catch (IOException e1) {
Log.p("image scaling failed " + e1.getMessage());
Dialog.show("Photo Upload", "Unable to scale photo:" + e1.getMessage(), "OK", null);
}
if (success) {
// open dialog and have user provide name
try {
String tmpFilepath = FileSystemStorage.getInstance().getAppHomePath() + filename;
Dialog.show("Image File", tmpFilepath, "OK", null);
uploadImage(tmpFilepath, name);
} catch (IOException err) {
Log.p("Image Upload Failed:" + err.getMessage());
Dialog.show("Picture Uploaded Failed", "Something prevented the upload of the image.", "OK", null);
}
}
}
}
}
}
我特意删掉了上面sn-p中的很多周边代码,专注于我认为重要的事情。
我保留了用于调试的 Dialog 语句,以便查看设备上的路径。如果我在模拟器中运行它,并选择一个文件,它上传正常,但是当我在 iPhone 上运行它时,发送到服务器的文件有 0 字节,并且 uploadImage 方法中的对话框将显示'0 photo( s) 上传”。在“tempfile.png”上使用 Storage.g.entrySize() 时,它显示文件的大小不是 0。如何正确引用此文件以将其发送到服务器。
【问题讨论】:
标签: codenameone