当前位置: 首页 > 知识库问答 >
问题:

使用multipart Resignfit 2上传图像

夏学名
2023-03-14
public class ServerResponse {

// variable name should be same as in the JSON response from PHP

@SerializedName("success")
boolean success;
@SerializedName("success_msg")
//@SerializedName("message")
String message;

String getMessage() {return message;
}

boolean getSuccess() {
    return success;
}
}
 public class ApiClient {



// public static final String BASE_URL="http://www.mytriangle.net16.net";
  public static final String BASE_URL="http://bsenterprise.in/webservice/";
 // public static final String BASE_URL = "http://mushtaq.16mb.com/";
private static Retrofit retrofit = null;
public static int unique_id;



public static Retrofit getClient() {
    if (retrofit==null) {
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}
}
public interface ApiService {


@Multipart

@POST("imageupload-1.php?")
//@POST("retrofit_example/upload_image.php")
Call<ServerResponse> uploadFile(
                                @Part MultipartBody.Part file1,
                               // @Part MultipartBody.Part file2,
                               //
                               // @Part("file") RequestBody name,
                               // @Part("serial_no") int serial_no);
                                @Part("serial_no") int serial_no);

}
public class MainActivity extends AppCompatActivity {

Button btnUpload, btnPickImage;
String mediaPath;
ImageView imgView1,imgView2;
String[] mediaColumns = { MediaStore.Video.Media._ID };
ProgressDialog progressDialog;

public static int choice;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    progressDialog = new ProgressDialog(this);
    progressDialog.setMessage("Uploading...");

    btnUpload = (Button) findViewById(R.id.upload);
    btnPickImage = (Button) findViewById(R.id.pick_img);
    imgView1 = (ImageView) findViewById(R.id.preview1);
    imgView2 = (ImageView) findViewById(R.id.preview2);

    choice=0;

    btnUpload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            uploadFile();
        }
    });

    imgView1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            choice=1;
            Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(galleryIntent, 0);
        }
    });

    imgView2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            choice=2;
            Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(galleryIntent, 0);
        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    try {
        // When an Image is picked
        if (requestCode == 0 && resultCode == RESULT_OK && null != data) {

            // Get the Image from data
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            assert cursor != null;
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            mediaPath = cursor.getString(columnIndex);
            // Set the Image in ImageView for Previewing the Media
            if(choice==1) {
                imgView1.setImageBitmap(BitmapFactory.decodeFile(mediaPath));
                cursor.close();
            }

          /*  else if(choice==2) {
                imgView2.setImageBitmap(BitmapFactory.decodeFile(mediaPath));
                cursor.close();
            }  */

        } else {
            Toast.makeText(this, "You haven't picked Image/Video", Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
    }

}



// Uploading Image/Video
private void uploadFile() {
    progressDialog.show();

    // Map is used to multipart the file using okhttp3.RequestBody
    File file1 = new File(mediaPath);
   // File file2 = new File(mediaPath);

    // Parsing any Media type file
    RequestBody requestBody1 = RequestBody.create(MediaType.parse("image/*"), file1);
   // RequestBody requestBody2 = RequestBody.create(MediaType.parse("*/*"), file2);

    MultipartBody.Part fileToUpload1 = MultipartBody.Part.createFormData("file", file1.getName(), requestBody1);
   // MultipartBody.Part fileToUpload2 = MultipartBody.Part.createFormData("file", file2.getName(), requestBody2);

    RequestBody filename1 = RequestBody.create(MediaType.parse("text/plain"), file1.getName());
   // RequestBody filename2 = RequestBody.create(MediaType.parse("text/plain"), file2.getName());

    ApiService getResponse = ApiClient.getClient().create(ApiService.class);
   // Call<ServerResponse> call = getResponse.uploadFile(fileToUpload1);
    Call<ServerResponse> call = getResponse.uploadFile(fileToUpload1,24);

    Toast.makeText(MainActivity.this,String.valueOf(file1),Toast.LENGTH_LONG).show();
    call.enqueue(new Callback<ServerResponse>() {

        @Override
        public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
            ServerResponse serverResponse = response.body();
            if (serverResponse != null) {
                if (serverResponse.getSuccess()) {
                    Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
                }
            } else {
                assert serverResponse != null;
                Log.v("Response", serverResponse.toString());
            }
            progressDialog.dismiss();
        }

        @Override
        public void onFailure(Call<ServerResponse> call, Throwable t) {

        }
    });
}

}
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.squareup.retrofit2:retrofit:2.0.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'

清单权限

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Android显示器输出

11-03 14:31:07.404 13163-13163/? D/TidaProvider: TidaProvider()
11-03 14:31:07.584 13163-13163/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
11-03 14:31:07.724 13163-13163/? I/ViewRootImpl: CPU Rendering VSync enable = true
11-03 14:31:07.724 13163-13184/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
11-03 14:31:07.734 13163-13163/? D/Atlas: Validating map...
11-03 14:31:07.744 13163-13163/? D/ActivityThreadInjector: clearCachedDrawables.
11-03 14:31:07.784 13163-13184/? I/Adreno-EGL: <qeglDrvAPI_eglInitialize:379>: EGL 1.4 QUALCOMM build: Nondeterministic_AU_msm8916_32_LA.BR.1.2.4_RB1__release_AU (Ic8ede1fb34)
                                           OpenGL ES Shader Compiler Version: E031.25.03.04
                                           Build Date: 12/10/15 Thu
                                           Local Branch: mybranch17178083
                                           Remote Branch: quic/LA.BR.1.2.4_rb1.30
                                           Local Patches: NONE
                                           Reconstruct Branch: NOTHING
11-03 14:31:07.784 13163-13184/? I/OpenGLRenderer: Initialized EGL, version 1.4
11-03 14:31:07.804 13163-13184/com.example.atanu.imageview D/OpenGLRenderer: Enabling debug mode 0
11-03 14:31:07.894 13163-13163/com.example.atanu.imageview I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@1b1dad79 time:103294123
11-03 14:31:14.813 13163-13163/com.example.atanu.imageview I/Timeline: Timeline: Activity_launch_request time:103300687
11-03 14:31:23.323 13163-13173/com.example.atanu.imageview W/art: Suspending all threads took: 9.429ms
11-03 14:31:24.283 13163-13163/com.example.atanu.imageview I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@1b1dad79 time:103310156
11-03 14:31:26.602 13163-13163/com.example.atanu.imageview I/Choreographer: Skipped 34 frames!  The application may be doing too much work on its main thread.
11-03 14:31:27.292 13163-13163/com.example.atanu.imageview I/ViewRootImpl: CPU Rendering VSync enable = true
11-03 14:31:27.372 13163-13163/com.example.atanu.imageview I/Choreographer: Skipped 45 frames!  The application may be doing too much work on its main thread.
11-03 14:31:28.002 13163-13163/com.example.atanu.imageview I/ViewRootImpl: CPU Rendering VSync enable = true
11-03 14:31:28.012 13163-13163/com.example.atanu.imageview I/Choreographer: Skipped 37 frames!  The application may be doing too much work on its main thread.
11-03 14:31:29.292 13163-13163/com.example.atanu.imageview I/Choreographer: Skipped 75 frames!  The application may be doing too much work on its main thread.
11-03 14:31:29.342 13163-13184/com.example.atanu.imageview V/RenderScript: Application requested CPU execution
11-03 14:31:29.362 13163-13184/com.example.atanu.imageview V/RenderScript: 0xb83d1510 Launching thread(s), CPUs 4
11-03 14:31:29.992 13163-13163/com.example.atanu.imageview I/Choreographer: Skipped 40 frames!  The application may be doing too much work on its main thread.

共有1个答案

刘乐童
2023-03-14

你应该这样上传你的文件

File file1 = new File(mediaPath);
int id=24;
// File file2 = new File(mediaPath);

RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file1);
MultipartBody.Part body = MultipartBody.Part.createFormData("photo", file.getName(), requestFile);

RequestBody requestBodyid = RequestBody.create(MediaType.parse("multipart/form-data"),id);


ApiService getResponse = ApiClient.getClient().create(ApiService.class);
// Call<ServerResponse> call = getResponse.uploadFile(fileToUpload1);
Call<ServerResponse> call = getResponse.uploadFile(body,requestBodyid);

而不是

RequestBody requestBody1 = RequestBody.create(MediaType.parse("image/*"), file1);

编辑:您忘记为ID创建请求正文。将这些添加到代码中。

RequestBody requestBodyid = RequestBody.create(MediaType.parse("multipart/form-data"), id);
 类似资料:
  • 经过一些研究,我发现了一个用于多部分文件上传的开放库。在我的情况下,我想上传一个图像使用PUT请求,其中的图像要么是从画廊或相机选择。以下是我正在使用的资源:1。https://github.com/gotev/android-upload-service2.https://www.simplifiedcoding.net/android-upload-image-to-server/#comme

  • 我正试图用Alamofire将图像上传到服务器,但我的代码不起作用。这是我的代码: 这是urlRequestWithComponents方法: 这就是我在控制台得到的: 请求{URL:http://tranthanhphongcntt.esy.es/task_manager/IOSFileUpload/ }响应可选({URL:http://tranthanhphongcntt.esy.es/tas

  • 我正在使用翻新上传图像/文件 在这里,我发布了我的API调用以上传图像 请帮助我如何为这个调用编写接口,我已经用@part和@PartMap试过了,但是不起作用

  • 我正在尝试实现一个非常基本的功能,从Android、iPhone和web客户端上传图像到google app Engine。多亏了这个博客,我完成了实现的初始版本: 然而,上传图像似乎总有两个步骤: 使用createUploadUrl()获取要发布到的初始上载URL。我附加了我使用的代码片段: 使用刚刚“获得”的URL发布图像 谢谢Rajat

  • 问题内容: 我使用,并将一些图像加载到上。 现在,我需要一次上传所有这些图像。正在使用,我该怎么做? 我浏览了文档,有一个名为的部分。但是,我无法上传中的图像。 *注意:我想以Byte Array 的形式上传图像。我怎样才能做到这一点?* 我到目前为止的代码, 问题答案: 试试这个。

  • 问题内容: 我正在使用Chrome驱动程序使用nightwatch.js运行前端测试。我需要测试图像上传是否正常工作,大概是通过提供的文件输入来进行的,因为在成功发布后会运行回调。 我知道可以使用Selenium Web驱动程序的sendKeys方法来完成。 您如何使用javascript和nightwatch.js完成此操作?您可以访问Selenium Webdriver或与其相关的界面吗? 问