2016-01-18 42 views
-4

我有一個需要複製的iOs應用程序。該應用程序使用照片上傳功能,使用下面的代碼:Android Photo Upload

-(void)writePhotoToDirectory{ 
    // check 
    if([appDelegate.myGlobals hasInternet]){ 
     // show cover 
     [appDelegate.myGlobals showCover:@"Saving photo. Please wait..." thisView:self.view]; 

     // vars 
     NSMutableData *postData = [NSMutableData data]; 
     NSString *boundry = @"0xMyLbOuNdArY"; 
     UIImage *uploadImage = [toUploadPhotos objectAtIndex:0]; 

     // generate guid 
     CFUUIDRef theGUID = CFUUIDCreate(NULL); 
     CFStringRef string = CFUUIDCreateString(NULL, theGUID); 
     CFRelease(theGUID); 
     NSString *uploadImageGUID = [NSString stringWithFormat:@"%@", (__bridge NSString *)string]; 
     NSString *uploadImageName = [NSString stringWithFormat:@"%lu-%@", (unsigned long)messageId, uploadImageGUID]; 

     // set 
     CGSize imageSize = CGSizeMake((unsigned long)round(uploadImage.size.width), (unsigned long)round(uploadImage.size.height)); 
     NSData *imageData = UIImageJPEGRepresentation(uploadImage, 0.9); 
     //NSLog(@"this image %@", imageData); 

     // set directory varable 
     [postData appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundry] dataUsingEncoding:NSUTF8StringEncoding]]; 
     [postData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"dirname\"; filename=\"%@\"\r\n\r\n", @""] dataUsingEncoding:NSUTF8StringEncoding]]; 

     // set image data 
     [postData appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundry] dataUsingEncoding:NSUTF8StringEncoding]]; 
     [postData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"uploaded\"; filename=\"%@.jpg\"\r\n\r\n", uploadImageName] dataUsingEncoding:NSUTF8StringEncoding]]; 
     [postData appendData:imageData]; 

     // end 
     [postData appendData: [[NSString stringWithFormat:@"\r\n--%@--\r\n", boundry] dataUsingEncoding:NSUTF8StringEncoding]]; 

     // url and request 
     NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/messagePhotoUploader.php", [appDelegate.myGlobals baseURL]]]; 
     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
     [request setHTTPMethod:@"POST"]; 
     [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)postData.length] forHTTPHeaderField:@"Content-Length"]; 
     [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundry] forHTTPHeaderField:@"Content-Type"]; 
     [request setHTTPBody:postData]; 

     NSLog(@"this post string %@?%@", url, [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding]); 

     // show network activity 
     [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; 

     // send 
     [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){ 
      // show network activity 
      [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; 

      // check 
      if(error) { 
       // handle error 
       [self webserviceDidNotSucceed:error]; 
      } 
      else{ 
       // handle success 
       //proceed 
      } 
     }]; 
    } 
    else{ 
     // alert 
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Internet" message:@"Oops! You currently do not have an internet connection. Please try again later." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
     [alert show]; 
    } 
} 

我的問題是我不明白這是如何工作,我需要做相同的功能到Android。我怎麼能這樣做。請幫忙。

編輯:

忘了補充的東西,我想:

private String multipartRequest(String urlTo, String filepath) { 
    HttpURLConnection connection = null; 
    DataOutputStream outputStream = null; 
    InputStream inputStream = null; 

    String twoHyphens = "--"; 
    String lineEnd = "\r\n"; 

    String result = ""; 

    int bytesRead, bytesAvailable, bufferSize; 
    byte[] buffer; 
    int maxBufferSize = 1 * 1024 * 1024; 


    try { 
     File file = new File(filepath); 
     FileInputStream fileInputStream = new FileInputStream(file); 

     URL url = new URL(urlTo); 
     connection = (HttpURLConnection) url.openConnection(); 

     connection.setDoInput(true); 
     connection.setDoOutput(true); 
     connection.setUseCaches(false); 

     connection.setRequestMethod("POST"); 
     connection.setRequestProperty("Connection", "Keep-Alive"); 
     connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0"); 
     connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); 



     outputStream = new DataOutputStream(connection.getOutputStream()); 
     outputStream.writeBytes(lineEnd+twoHyphens + boundary + lineEnd); 
     outputStream.writeBytes("Content-Disposition: form-data; name=\"dirname\"; filename=\"" + this.fileName + "\"" + lineEnd+lineEnd); 


     outputStream.writeBytes(lineEnd+twoHyphens+boundary+lineEnd); 
     outputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded\"; filename=\"" + this.fileName + ".jpg\"" + lineEnd+lineEnd); 
     outputStream.writeBytes(imageData); 

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

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

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

     if (200 != connection.getResponseCode()) { 
      callBacks.didUploadFailed(connection.getResponseCode()+"",connection.getResponseMessage(),this); 
     } 

     inputStream = connection.getInputStream(); 

     result = this.convertStreamToString(inputStream); 
     Log.e(TAG,">>>>>"+result); 

     fileInputStream.close(); 
     inputStream.close(); 
     outputStream.flush(); 
     outputStream.close(); 

     return result; 
    } catch (Exception e) { 
     e.printStackTrace(); 

     callBacks.didUploadFailed("-1",e.getLocalizedMessage(),this); 
    } 

    return ""; 
} 
+1

所以基本上你想讓我們爲你轉換上面的代碼? – k0sh

+0

解釋這是如何工作的。 – MetaSnarf

+0

你甚至google嗎? – k0sh

回答

0

所以很多的調整和研究後,我發現我通過圖像的方式是錯誤的。在昨天的代碼中,我將圖像位圖轉換爲base64字符串,然後將該字符串轉換爲字節數組。這是錯誤的,因爲我有位圖圖像轉換爲字節數組直接:

 java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); 
     bitmap.compress(Bitmap.CompressFormat.JPEG,100,baos); 

     byte[] b = baos.toByteArray(); 
     imageBytes = b; 

,並把它傳遞給我的輸出流outputStream.writeBytes(imageData);一部分,將其更改爲outputStream.write(imageBytes);。 我希望這可以幫助像我這樣的初學者無法從SO的'專家'中獲得幫助。