Android 照片上传

Android Photo Upload

我有一个 iOs 应用程序需要复制。该应用使用以下代码使用照片上传功能:

    -(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 "";
}

所以经过大量的调整和研究,我发现我传递图像的方式是错误的。在我昨天的代码中,我将图像位图转换为 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 'experts' 获得帮助的初学者。