本文介绍了改造(2.0 Beta2中)多部分文件上传不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的广场改造2.0 Beta2的。我试图按照我想上传位图图像到服务器,但不知何故code不工作。我曾尝试使用邮递员测试我的服务器和我能张贴的照片,甚至能找回它。这是我的烧瓶控制器。

I am using Square Retrofit version 2.0 beta2. I have tried to follow this tutorial .I am trying to upload a bitmap image to the server but somehow code is not working. I have tried testing my server using postman and I am able to post photo and even able to retrieve it. Here is my flask controller.

@app.route('/api/photo/user/<int:user_id>', methods=["POST"])
    def post_user_photo(user_id):
        app.logger.info("post_user_photo=> user_id:{}, photo: {}".format(
            user_id,
            request.files['photo'].filename,
        ))
        user = User.query.get_or_404(user_id)
        try:
            user.photo = request.files['photo'].read()
        except Exception as e:
            app.logger.exception(e)
            db.session.rollback()
            raise
        db.session.commit()
        return "", codes.no_content

我已经使用了邮递员来测试我的控制器,并在这里是邮递员产生的请求。

I have used the postman to test my controller and here is the request generated by postman.

POST /api/photo/user/5 HTTP/1.1
Host: blooming-cliffs-9672.herokuapp.com
Cache-Control: no-cache
Postman-Token: 8117fb79-4781-449d-7d22-237c49b53389
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="photo"; filename="sfsu.jpg"
Content-Type: image/jpeg


----WebKitFormBoundary7MA4YWxkTrZu0gW

我所定义的改造服务和上传图片,这里是我的Andr​​oid code。接口部分

I have defined the retrofit service and the to upload the image and here is my Android code. Interface part

  @Multipart
    @POST("/api/photo/user/{userId}")
    Call<Void> uploadUserProfilePhoto(@Path("userId") Integer userId, @Part("photo") RequestBody photo);

下面的客户端部分建设者

Here client builder part

  public static BeamItService getService(){
        if (service == null) {
            OkHttpClient client = new OkHttpClient();
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            HttpLoggingInterceptor interceptor2 = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);

            client.interceptors().add(interceptor);
            client.interceptors().add(interceptor2);

            service =  new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build().create(BeamItService.class);
        }
        return service;
    }

这是Android活动code它试图上传的位图。

And here is the Android activity code which tries to upload the bitmap.

private void uploadProfilePhoto(){
        BeamItService service = BeamItServiceTransport.getService();

        MediaType MEDIA_TYPE_PNG = MediaType.parse("image/jpeg");
        byte [] data = BitmapUtility.getBitmapToBytes(((BitmapDrawable) ivProfilePhoto.getDrawable()).getBitmap());
        Log.d(TAG, String.format("Profile detals => user_id: %d, size of data: %d", 5, data.length));

        RequestBody requestBody1 = RequestBody.create(MEDIA_TYPE_PNG,
                                                    data);
        Log.d(TAG, "requestBody: " + requestBody1.toString());
        RequestBody requestBody2 = new MultipartBuilder()
                .type(MultipartBuilder.FORM)
                .addPart(Headers.of("Content-Disposition", "form-data; name=\"photo\"; filename=\"t.jpg\""),
                        requestBody1)
                .build();
        Log.d(TAG, "requestBody: " + requestBody2.toString());
//        ProfileDetails profileDetails = new DBHelper(this).fetchProfileDetails();

        Call<Void> call = service.uploadUserProfilePhoto(5, requestBody2);
        call.enqueue(new ProfilePhotoUploadCallback());
    }

    private class ProfilePhotoUploadCallback implements Callback<Void> {

        @Override
        public void onResponse(Response<Void> response, Retrofit retrofit) {
            Log.d(TAG, String.format("ProfilePhotoUploadCallback=> code: %d", response.code()));
        }

        @Override
        public void onFailure(Throwable t) {

        }
    }

但它无法上传,烧瓶应用程序返回每次状态code 400。我试图把断点在烧瓶中的应用程序,但要求甚至没有到达那里。
这里是服务器日志

But it fails to upload it, flask app returns status code 400 every time. I tried to put the breakpoint in the flask app, but request doesn't even reach there.here is the server log

2015-11-02T06:05:42.288574+00:00 heroku[router]: at=info method=POST path="/api/photo/user/5" host=blooming-cliffs-9672.herokuapp.com request_id=2cc8b6c8-f12a-4e4b-8279-cedfc39712f2 fwd="204.28.113.240" dyno=web.1 connect=1ms service=88ms status=400 bytes=347
2015-11-02T06:05:42.209347+00:00 app[web.1]: [2015-11-02 06:05:42 +0000] [11] [DEBUG] POST /api/photo/user/5

我也试图使改造截击和日志的请求和响应,但我没有得到整个POST请求主体。下面是Android日志。

I also tried to enable the retrofit intercepter and log the request and response, but I don't get the entire POST request body. Here is the Android log.

    11-02 00:24:22.119 3904-4382/com.contactsharing.beamit D/OkHttp: --> POST /api/photo/user/5 HTTP/1.1
11-02 00:24:22.119 3904-4382/com.contactsharing.beamit D/OkHttp: Content-Type: multipart/form-data; boundary=4031e177-0e4b-4f16-abe8-20c54e506846
11-02 00:24:22.120 3904-4382/com.contactsharing.beamit D/OkHttp: Content-Length: 17171
11-02 00:24:22.120 3904-4382/com.contactsharing.beamit D/OkHttp: Host: blooming-cliffs-9672.herokuapp.com
11-02 00:24:22.120 3904-4382/com.contactsharing.beamit D/OkHttp: Connection: Keep-Alive
11-02 00:24:22.120 3904-4382/com.contactsharing.beamit D/OkHttp: Accept-Encoding: gzip
11-02 00:24:22.120 3904-4382/com.contactsharing.beamit D/OkHttp: User-Agent: okhttp/2.6.0-SNAPSHOT
11-02 00:24:22.120 3904-4382/com.contactsharing.beamit D/OkHttp: --> END POST
11-02 00:24:22.179 3904-4537/com.contactsharing.beamit I/DBHelper: Updated row: 1
11-02 00:24:22.316 3904-4382/com.contactsharing.beamit D/OkHttp: <-- HTTP/1.1 400 BAD REQUEST (195ms)
11-02 00:24:22.316 3904-4382/com.contactsharing.beamit D/OkHttp: Connection: keep-alive
11-02 00:24:22.316 3904-4382/com.contactsharing.beamit D/OkHttp: Server: gunicorn/19.3.0
11-02 00:24:22.316 3904-4382/com.contactsharing.beamit D/OkHttp: Date: Mon, 02 Nov 2015 08:24:22 GMT
11-02 00:24:22.316 3904-4382/com.contactsharing.beamit D/OkHttp: Content-Type: text/html
11-02 00:24:22.316 3904-4382/com.contactsharing.beamit D/OkHttp: Content-Length: 192
11-02 00:24:22.316 3904-4382/com.contactsharing.beamit D/OkHttp: Via: 1.1 vegur
11-02 00:24:22.316 3904-4382/com.contactsharing.beamit D/OkHttp: OkHttp-Selected-Protocol: http/1.1
11-02 00:24:22.316 3904-4382/com.contactsharing.beamit D/OkHttp: OkHttp-Sent-Millis: 1446452662120
11-02 00:24:22.316 3904-4382/com.contactsharing.beamit D/OkHttp: OkHttp-Received-Millis: 1446452662316
11-02 00:24:22.316 3904-4382/com.contactsharing.beamit D/OkHttp: <-- END HTTP

请帮忙,我卡住,无法取得任何进展。

Please help, I am stuck and not able to make any progress.

推荐答案

您在这里筑巢multipart请求体(一个多内一个多)。

You are nesting a multipart request body here (A multipart within a multipart).

实施了类似的东西最近,不是使用 @Multipart @part 您可以使用 @Body MultipartBuilder

Implemented something similar recently, instead of using @Multipart and @Part you can use @Body with MultipartBuilder.

@POST("/api/photo/user/{userId}")
Call<Void> uploadUserProfilePhoto(@Path("userId") Integer userId, @Body RequestBody photo);

然后,而不是使用 MultipartBuilder.addPart(...)使用 MultipartBuilder.addFormDataPart(名,文件名,requestBody)

private void uploadProfilePhoto() {
    BeamItService service = BeamItServiceTransport.getService();

    MediaType MEDIA_TYPE_PNG = MediaType.parse("image/jpeg");
    byte [] data = BitmapUtility.getBitmapToBytes(((BitmapDrawable) ivProfilePhoto.getDrawable()).getBitmap());
    Log.d(TAG, String.format("Profile detals => user_id: %d, size of data: %d", 5, data.length));

    RequestBody requestBody1 = RequestBody.create(MEDIA_TYPE_PNG, data);
    Log.d(TAG, "requestBody: " + requestBody1.toString());
    RequestBody requestBody2 = new MultipartBuilder()
            .type(MultipartBuilder.FORM)
            .addFormDataPart("photo", "t.jpg", requestBody1)
            .build();
    Log.d(TAG, "requestBody: " + requestBody2.toString());
//  ProfileDetails profileDetails = new DBHelper(this).fetchProfileDetails();

    Call<Void> call = service.uploadUserProfilePhoto(5, requestBody2);
    call.enqueue(new ProfilePhotoUploadCallback());
}

这篇关于改造(2.0 Beta2中)多部分文件上传不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 14:01