phonegap(cordova)文件上传(Java,PHP)

31 篇文章 0 订阅
13 篇文章 0 订阅


phonegap(cordova)文件上传(Java,PHP)服务器:
<h2>phonegap中的FileTransfer对象介绍:</h2>
<p>http://docs.phonegap.com/en/1.6.1/cordova_file_file.md.html#FileTransfer
</p>
<p>&nbsp;</p>
<p>今天的代码为同学所整理。在此记下来,供以后参考</p>
<p>&nbsp;</p>
<p>FileTransfer
&nbsp;
is an object that allows you to upload files to a server or download files from a server.
</p>
<p>&nbsp;</p>
<p>用于传<strong>文件</strong>到服务器端</p>
<p>&nbsp;</p>
<p>它里面有示例,写得已经是非常的详细,其中有一段:</p>
<pre>var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=fileURI.substr(fileURI.lastIndexOf('/')+1);
options.mimeType="text/plain";</pre>
<p>&nbsp;</p>
<p>前端的完整版可以参考:http://www.oschina.net/question/200138_34919
 </p>
<p>&nbsp;</p>
<p>今天在做图片上传的时候,怎整也无法在后端获取<strong>文件</strong>流,其中的Java逻辑如下:</p>
<pre>int MAX_SIZE = 102400 * 102400;

   DataInputStream in = null;
   FileOutputStream fileOut = null;

   String contentType = request.getContentType();
   try {
    if (contentType.indexOf("multipart/form-data") &gt;= 0) {
     in = new DataInputStream(request.getInputStream());
     int formDataLength = request.getContentLength();
     if (formDataLength &gt; MAX_SIZE) {
      return;
     }
     byte dataBytes[] = new byte[formDataLength];
     int byteRead = 0;
     int totalBytesRead = 0;
     while (totalBytesRead &lt; 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("\n"));
     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("\n", pos) + 1;
     pos = file.indexOf("\n", pos) + 1;
     pos = file.indexOf("\n", pos) + 1;
     int boundaryLocation = file.indexOf(boundary, pos) - 4;
     // 取得<strong>文件</strong>数据的开始的位置
     int startPos = ((file.substring(0, pos)).getBytes()).length;
     // 取得<strong>文件</strong>数据的结束的位置
     int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;

     // 创建<strong>文件</strong>的写出类
     fileOut = new FileOutputStream(System.getProperty("java.io.tmpdir") + "/aa.jpg");
     // 保存<strong>文件</strong>的数据
     fileOut.write(dataBytes, startPos, (endPos - startPos));
     fileOut.close();
    }
   } catch (Exception ex) {
    throw new ServletException(ex.getMessage());
   }</pre>
<p>&nbsp;后来才发现,原来是少了一个致命的参数:options.chunkedMode = false;</p>
<p>&nbsp;</p>
<p>关于chunkedMode的解析,请看:http://www.issociate.de/board/post/368589/How_to_force_the_apache_transfer_the_data_in_chunked_mode?.html
</p>
<p>&nbsp;</p>
<p>大意是:如果<strong>文件</strong>长度无法预知时,使用chuckedMode模式传输,现在传输的是图片,大小已经知道,不知道为何apache服务器处理不过来,一定要将chunkedMode设成false,至此上传成功,感觉同学指点</p>
<p>&nbsp;</p>
<p>为了这个参数,我还对比了php版本的<strong>文件</strong>上传:php的server端这样写的:</p>
<pre>&lt;?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"]);
}

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


// 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."&lt;br&gt;";
                echo "&lt;img src='".$baseURI."?image=".$curimg."&amp;rnd=".uniqid()."'&gt;&lt;br&gt;";
            }
        }
    }
    else {
        echo "No images on server";
    }
}
?&gt;</pre>
<p>&nbsp;php的代码参考:https://github.com/brycecurtis/articles/tree/master/CameraUpload
</p>
<p>&nbsp;</p>
<p>代码说明及解说在:https://www.ibm.com/developerworks/mydeveloperworks/blogs/94e7fded-7162-445e-8ceb-97a2140866a9/entry/upload_a_picture_using_phonegap_on_android8?lang=en
</p>
<p>&nbsp;</p>
<p>php版本的这个前端代码:</p>
<pre>// 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";
            options.chunkedMode = false;


            // 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);
        }</pre>
<p>&nbsp;确实是含有chunkedMode=false的设置,并在本机运行通过。</p>

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值