phonegap文件下传(Java,PHP)

php中文网
发布: 2016-06-13 13:19:52
原创
1039人浏览过

phonegap文件上传(Java,PHP)

phpnegap文件上传

phonegap中的FileTransfer对象介绍:

http://docs.phonegap.com/en/1.6.1/cordova_file_file.md.html#FileTransfer

?

今天的代码为同学所整理。在此记下来,供以后参考

?

FileTransfer ? is an object that allows you to upload files to a server or download files from a server.

?

用于传文件到服务器端

立即学习PHP免费学习笔记(深入)”;

?

它里面有示例,写得已经是非常的详细,其中有一段:

var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=fileURI.substr(fileURI.lastIndexOf('/')+1);
options.mimeType="text/plain";
登录后复制

?

前端的完整版可以参考:http://www.oschina.net/question/200138_34919

?

今天在做图片上传的时候,怎整也无法在后端获取文件流,其中的Java逻辑如下:

int MAX_SIZE = 102400 * 102400;

			DataInputStream in = null;
			FileOutputStream fileOut = null;

			String contentType = request.getContentType();
			try {
				if (contentType.indexOf("multipart/form-data") >= 0) {
					in = new DataInputStream(request.getInputStream());
					int formDataLength = request.getContentLength();
					if (formDataLength > MAX_SIZE) {
						return;
					}
					byte dataBytes[] = new byte[formDataLength];
					int byteRead = 0;
					int totalBytesRead = 0;
					while (totalBytesRead < formDataLength) {
						byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
						totalBytesRead += byteRead;
					}
					String file = new String(dataBytes);
					String saveFile = file.substring(file.indexOf("filename="") + 10);
					saveFile = saveFile.substring(0, saveFile.indexOf("
"));
					saveFile = saveFile.substring(saveFile.lastIndexOf("\") + 1, saveFile.indexOf("""));
					int lastIndex = contentType.lastIndexOf("=");
					String boundary = contentType.substring(lastIndex + 1,contentType.length());

					int pos;
					pos = file.indexOf("filename="");
					pos = file.indexOf("
", pos) + 1;
					pos = file.indexOf("
", pos) + 1;
					pos = file.indexOf("
", pos) + 1;
					int boundaryLocation = file.indexOf(boundary, pos) - 4;
					// 取得文件数据的开始的位置
					int startPos = ((file.substring(0, pos)).getBytes()).length;
					// 取得文件数据的结束的位置
					int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;

					// 创建文件的写出类
					fileOut = new FileOutputStream(System.getProperty("java.io.tmpdir") + "/aa.jpg");
					// 保存文件的数据
					fileOut.write(dataBytes, startPos, (endPos - startPos));
					fileOut.close();
				} 
			} catch (Exception ex) {
				throw new ServletException(ex.getMessage());
			}
登录后复制

?后来才发现,原来是少了一个致命的参数:options.chunkedMode = false;

巧文书
巧文书

巧文书是一款AI写标书、AI写方案的产品。通过自研的先进AI大模型,精准解析招标文件,智能生成投标内容。

巧文书 61
查看详情 巧文书

?

关于chunkedMode的解析,请看:http://www.issociate.de/board/post/368589/How_to_force_the_apache_transfer_the_data_in_chunked_mode?.html

?

大意是:如果文件长度无法预知时,使用chuckedMode模式传输,现在传输的是图片,大小已经知道,不知道为何apache服务器处理不过来,一定要将chunkedMode设成false,至此上传成功,感觉同学指点

?

为了这个参数,我还对比了php版本的文件上传:php的server端这样写的:

<?php
// Directory where uploaded images are saved
$dirname = "/tmp/phonegap/uploads"; 

// If uploading file
if ($_FILES) {
    print_r($_FILES);
    mkdir ($dirname, 0777, true); 
    move_uploaded_file($_FILES["file"]["tmp_name"],$dirname."/".$_FILES["file"]["name"]);
}

<span style="color: #ff0000;">// If retrieving an image
else if (isset($_GET['image'])) {
    $file = $dirname."/".$_GET['image'];

    // Specify as jpeg
    header('Content-type: image/jpeg');
  
    // Resize image for mobile
    list($width, $height) = getimagesize($file); 
    $newWidth = 120.0; 
    $size = $newWidth / $width;
    $newHeight = $height * $size; 
    $resizedImage = imagecreatetruecolor($newWidth, $newHeight); 
    $image = imagecreatefromjpeg($file); 
    imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); 
    imagejpeg($resizedImage, null, 80); 
}</span>



// If displaying images
else {
    $baseURI = "http://".$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['REQUEST_URI'];
    $images = scandir($dirname);
    $ignore = Array(".", "..");
    if ($images) {
        foreach($images as $curimg){ 
            if (!in_array($curimg, $ignore)) {
                echo "Image: ".$curimg."<br>";
                echo "<img  src='".$baseURI."?image=".$curimg."&rnd=".uniqid()."' alt=" phonegap文件下传(Java,PHP) " ><br>"; 
            }
        }
    }
    else {
        echo "No images on server";
    }
}
?>
登录后复制

?php的代码参考:https://github.com/brycecurtis/articles/tree/master/CameraUpload

?

代码说明及解说在:https://www.ibm.com/developerworks/mydeveloperworks/blogs/94e7fded-7162-445e-8ceb-97a2140866a9/entry/upload_a_picture_using_phonegap_on_android8?lang=en

?

php版本的这个前端代码:

// Verify server has been entered
        server = document.getElementById('serverUrl').value;
        if (server) {
        	
            // Specify transfer options
            var options = new FileUploadOptions();
            options.fileKey="file";
            options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
            options.mimeType="image/jpeg";
            <span style="color: #ff0000;">options.chunkedMode = false;</span>



            // Transfer picture to server
            var ft = new FileTransfer();
            ft.upload(imageURI, server, function(r) {
                document.getElementById('camera_status').innerHTML = "Upload successful: "+r.bytesSent+" bytes uploaded.";            	
            }, function(error) {
                document.getElementById('camera_status').innerHTML = "Upload failed: Code = "+error.code;            	
            }, options);
        }
登录后复制

?确实是含有chunkedMode=false的设置,并在本机运行通过。

PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号