Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/231.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 安卓照片上传_Android_Image Uploading - Fatal编程技术网

Android 安卓照片上传

Android 安卓照片上传,android,image-uploading,Android,Image Uploading,我有一个需要复制的iOs应用程序。应用程序使用照片上传功能,代码如下: -(void)writePhotoToDirectory{ // check if([appDelegate.myGlobals hasInternet]){ // show cover [appDelegate.myGlobals showCover:@"Saving photo. Please wait..." thisView:self.view];

我有一个需要复制的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.writeBytesimageData;part并将其更改为outputStream.writeimageBytes;。
我希望这能帮助像我这样的初学者,他们无法从SO的“专家”那里得到帮助。

所以基本上你想让我们为你转换上述代码?这是一个如何工作的解释。你甚至用谷歌搜索过吗?是的,我想确认我对这个问题的理解是否正确。如果我做得对的话