2017-05-25 88 views
0

我有使用Monaca/Onsen UI和AngularJS构建的跨平台应用程序。 该应用程序允许用户拍摄图像(照片),这是按预期工作。使用PHP将图像从应用程序上传到服务器

接下来,我想将图像上传到我的服务器以供存储和将来使用。

我有应用程序图像捕获按预期工作,我在服务器上实现了一个PHP解决方案,似乎正在工作,但我似乎无法看到图像。

我的采集和上传应用程序的代码如下所示(目前我刚刚访问图像库,并选择图像进行测试 - 而不是捕捉他们 - 但是这两种解决方案的工作):

$scope.takePicture = function getImage() { 
    navigator.camera.getPicture(uploadPhoto, function (message) { 
     alert('get picture failed'); 
    }, { 
     quality: 100, destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY 
    }); 
} 

function uploadPhoto(imageURI) { 
    var options = new FileUploadOptions(); 
    options.fileKey = "file"; 
    options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1); 
    options.mimeType = "image/jpeg"; 
    var params = new Object(); 
    params.value1 = "test"; 
    params.value2 = "param"; 
    options.params = params; 
    options.chunkedMode = false; 

    var ft = new FileTransfer(); 
    ft.upload(imageURI, "http://mysite/public/api/savephotos.php", function (result) { 
     alert("Success: " + JSON.stringify(result)); // Success: {"bytesSent":42468,"responseCode":200,"response":"","objectId":""} 
    }, function (error) { 
     alert("Fail: " + JSON.stringify(error)); 
    }, options); 
} 

成功回应似乎图像正在发送,但当我检查图像应保存到的文件夹(C:\ xampp \ htdocs \ public \ api \ upload)时,该文件夹为空。服务器端详细信息是使用AWS上托管的Laravel框架的Sximo模板。

,处理服务器端保存PHP代码看起来如下:

<?php 
    // Connect to Database 
    $DB_HOST = 'localhost'; 
    $DB_USER = 'root'; 
    $DB_PASS = ''; 
    $DB_NAME = 'myDB'; 

    $mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME); 

    if (mysqli_connect_errno()) { 
     printf("Connect failed: %s\n", mysqli_connect_error()); 
     exit(); 
    } 

    // Allow Headers 
    header('Access-Control-Allow-Origin: *'); 
    $new_image_name = urldecode($_FILES["file"]["name"]).".jpg"; 
    // Move files into upload folder 
    move_uploaded_file($_FILES["file"]["tmp_name"], 'C:\xampp\htdocs\public\api\upload'.$new_image_name); 

mysqli_close($mysqli); 

然而,C:\ XAMPP \ htdocs中\ PUBLIC \ API \上传是空的 - 没有发送给它的图像。我确实有一个名为uploadimage的文件,该文件已经发送到目录* C:\ xampp \ htdocs \ public \ api *,该文件似乎每次测试都会更新 - 但这是一个空文件(0kb)。

我在哪里出错了?

回答

0

这是我用来从图库应用程序发送图像服务器asynktask

public static class requestPostReportPhoto extends AsyncTask<String, Void, String> { 

    Bitmap image; 
    String JSON_STRING; 

    @Override 
    protected void onPreExecute(){ 
     String fileUrl = Environment.getExternalStorageDirectory()+"/"+Environment.DIRECTORY_DCIM+"/"+"albumName"+"/"+"photoName"; 
     image = BitmapFactory.decodeFile(fileUrl); 

    } 

    @Override 
    protected String doInBackground(String... params) { 
     String fileUrl = Environment.getExternalStorageDirectory()+"/"+Environment.DIRECTORY_DCIM+"/"+"albumName"+"/"+"photoName"; 

     DataOutputStream dos = null; 
     String lineEnd = "\r\n"; 
     String twoHyphens = "--"; 
     String boundary = "*****"; 
     HttpURLConnection connection = null; 
     int bytesRead, bytesAvailable, bufferSize; 
     byte[] buffer; 
     int maxBufferSize = 1 * 1024 * 1024; 
     String response = "Error"; 



     String urlString = "yourUrlServer"; 

     try { 
      File file = new File(fileUrl); 
      FileInputStream fileInputStream = new FileInputStream(file); 
      URL url = new URL(urlString); 
      connection = (HttpURLConnection) url.openConnection(); 
      connection.setDoInput(true); // Allow Inputs 
      connection.setDoOutput(true); // Allow Outputs 
      connection.setUseCaches(false); 
      connection.setRequestMethod("POST"); 
      connection.setRequestProperty("Connection", "Keep-Alive"); 
      connection.addRequestProperty("content-type", "multipart/form-data; boundary=" + boundary); 


      dos = new DataOutputStream(connection.getOutputStream()); 

      dos.writeBytes(twoHyphens + boundary + lineEnd); 
      dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + "PHOTONAME" + "\"" + lineEnd); 
      dos.writeBytes(lineEnd); 



      Log.d("MediaPlayer", "Headers are written"); 

      bytesAvailable = fileInputStream.available(); 
      bufferSize = Math.min(bytesAvailable, maxBufferSize); 
      buffer = new byte[bufferSize]; 


      bytesRead = fileInputStream.read(buffer, 0, bufferSize); 

      while (bytesRead > 0) { 
       dos.write(buffer, 0, bufferSize); 
       bytesAvailable = fileInputStream.available(); 
       bufferSize = Math.min(bytesAvailable, maxBufferSize); 
       bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
      } 


      dos.writeBytes(lineEnd); 

      dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 

      StringBuilder responseSB = new StringBuilder(); 
      int result = connection.getResponseCode(); 
      BufferedReader br; 
      // 401 - 422 - 403 - 404 - 500 
      if (result == 401 || result == 422 || result == 403 || result == 404 || result == 500) 
      { 
       br = new BufferedReader(new InputStreamReader(connection.getErrorStream())); 
      } 
      else { 
       br = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
      } 
      while ((JSON_STRING = br.readLine()) != null) 
       responseSB.append(JSON_STRING+ "\n"); 

      Log.d("MediaPlayer","File is written"); 
      fileInputStream.close(); 
      dos.flush(); 
      dos.close(); 
      br.close(); 


      response = responseSB.toString().trim(); 

     } catch (IOException ioe) { 
      Log.d("MediaPlayer", "error: " + ioe.getMessage(), ioe); 
     } 

     return response; 

    } 


    @Override 
    protected void onPostExecute(String result) { 
     Log.d("SERVER RESPONSE ->",result) 
    } 





    @Override 
    protected void onProgressUpdate(Void... values) { 
     super.onProgressUpdate(values); 
    } 

} 
相关问题