Android Photo Upload

时间:2016-01-18 02:49:47

标签: android image-uploading

我有一个需要复制的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 "";
}

1 个答案:

答案 0 :(得分:0)

经过大量的调整和研究后,我发现我通过图像的方式是错误的。在我昨天的代码中,我将图像位图转换为base64字符串,然后将该字符串转换为bytes数组。这是错误的,因为我必须直接将位图图像转换为字节数组:

        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的“专家”那里获得帮助。