2015-12-30 4 views
-1

Я пытаюсь преобразовать некоторый код iOS, который я использую, чтобы загрузить изображение на устройстве Android с помощью Retrofit 2.0. Моя попытка в этом не работает, и я не знаю, почему. Кажется, сервер не получил изображение.Загрузка изображения с помощью Retrofit 2

Здесь работает IOS код:

NSData *imageData = UIImageJPEGRepresentation(image, 90); 
// setting up the URL to post to 
NSString *urlString = [NSString stringWithFormat:@"http://%@/uploadPicture.php", [[NSUserDefaults standardUserDefaults] stringForKey:@"serviceIPAddress"]]; 

// setting up the request object now 
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
[request setURL:[NSURL URLWithString:urlString]]; 
[request setHTTPMethod:@"POST"]; 

/* 
add some header info now 
we always need a boundary when we post a file 
also we need to set the content type 

You might want to generate a random boundary.. this is just the same 
as my output from wireshark on a valid html post 
*/ 
NSString *boundary = @"---------------------------14737809831466499882746641449"; 
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary]; 
[request addValue:contentType forHTTPHeaderField: @"Content-Type"]; 

/* 
now lets create the body of the post 
*/ 
NSMutableData *body = [NSMutableData data]; 
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@.jpg\"\r\n", persistentID] dataUsingEncoding:NSUTF8StringEncoding]]; 
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
[body appendData:[NSData dataWithData:imageData]]; 
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
// setting the body of the post to the reqeust 
[request setHTTPBody:body]; 

// now lets make the connection to the web 
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; 

Это неисправной Android код:

@POST 
Call<Void> uploadImage(@Url String url, @Body RequestBody imageFile); 

private void uploadInventoryImage(InventoryItem item, Uri imageUri, final boolean isNewItem) { 

    final File imageFile = new File(imageUri.getPath()); 
    final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "MyDir" + File.separator); 
    final String imageName = item.getPersistentId() + ".jpg"; 
    final File renamedImageFile= new File(root, imageName); 

    if (imageFile.renameTo(renamedImageFile)) { 

     SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext); 
     String uploadUrl = "http://" + settings.getString("serverPath", "") + "/mamobile/uploadPicture.php"; 

     RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpeg"), renamedImageFile); 
     MultipartBuilder multipartBuilder = new MultipartBuilder("---------------------------14737809831466499882746641449"); 
     multipartBuilder.addFormDataPart("userfile", renamedImageFile.getName(), fileBody); 
     RequestBody fileRequestBody = multipartBuilder.build(); 

     mApiClient.getInventoryService().uploadImage(uploadUrl, fileRequestBody).enqueue(new Callback<Void>() { 
      @Override 
      public void onResponse(Response<Void> response, Retrofit retrofit) { 
       //upload image sucess 
       if (isNewItem) { 
        mBus.post(new InventoryEditEvent.OnUpdateSuccess()); 
       } else { 
        mBus.post(new InventoryEditEvent.OnNewSuccess()); 
       } 
      } 

      @Override 
      public void onFailure(Throwable error) { 
       if (error != null && error.getMessage() != null) { 
        mBus.post(new InventoryEditEvent.OnUploadImageFailure(error.getMessage(), -1)); 
       } else { 
        mBus.post(new InventoryEditEvent.OnUploadImageFailure("Unknown Error", -1)); 
       } 
      } 
     }); 


    } else { 
     //file name failed; 
     mBus.post(new InventoryEditEvent.OnUploadImageFailure("Could not rename image", -1)); 
    } 
} 

Запрос возвращается как успешный, но сервер не кажется, чтобы получить изображение.

ответ

0

Во-первых, попробуйте изменить описание метода услуги в этом

@Multipart 
@POST 
Call<Void> uploadImage(@Url String url, @Part("description") String description, @Part("myfile\"; filename=\"image.png\"") RequestBody imageFile); 

description часть не является обязательным. Просто хедз-ап, вам нужно записать файл с жестким кодом в аннотацию @Part. Его способ обхода существующей ошибки OkHttp, которая по умолчанию является встроенным клиентом retrofit2 http.

Для получения подробной документации по загрузке файлов используйте, пожалуйста, this.

+0

Мне нужно динамически изменять имя файла. Если я не могу этого сделать, мне может потребоваться переписать эту часть моего api :( – Hackmodford

Смежные вопросы