Android 如何使用文件上传改型传递请求字符串参数?
如何使用改型发送请求字符串param。我已经提交了下面的代码。这里介绍如何添加字符串param并发送到服务器 AppConfig:Android 如何使用文件上传改型传递请求字符串参数?,android,file-upload,parameters,retrofit,Android,File Upload,Parameters,Retrofit,如何使用改型发送请求字符串param。我已经提交了下面的代码。这里介绍如何添加字符串param并发送到服务器 AppConfig: 公共类AppConfig{ public static String BASE_URL = "http://104.239.173.64/peoplecaddie-api"; public static Retrofit getRetrofit() { return new Retrofit.Builder() .baseUrl
公共类AppConfig{
public static String BASE_URL = "http://104.239.173.64/peoplecaddie-api";
public static Retrofit getRetrofit() {
return new Retrofit.Builder()
.baseUrl(AppConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
ApiConfig:
public interface ApiConfig {
@Multipart
@POST("/general/Candidate/fileUpload")
Call<ServerResponse> upload(
@Header("Authorization") String authorization,
@PartMap Map<String, RequestBody> map
);
}
主要活动:
public类MainActivity扩展了AppCompatActivity{
按钮btnUpload、btnPickImage、btnPickVideo;
字符串中介路径;
ImageView-imgView;
字符串[]mediaColumns={MediaStore.Video.Media.\u ID};
进行对话进行对话;
/**
*注意:这是自动生成的,用于实现应用程序索引API。
*看https://g.co/AppIndexing/AndroidStudio 了解更多信息。
*/
私人GoogleapClient客户2;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressDialog=新建progressDialog(此);
progressDialog.setMessage(“上载…”);
btnUpload=(按钮)findviewbyd(R.id.upload);
btnPickImage=(按钮)findViewById(R.id.pick\u img);
btnPickVideo=(按钮)findviewbyd(R.id.pick_vdo);
imgView=(ImageView)findViewById(R.id.preview);
btnUpload.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
上传文件();
}
});
btnPickImage.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
Intent gallerycontent=新意图(Intent.ACTION\u PICK,
MediaStore.Images.Media.EXTERNAL\u CONTENT\u URI);
startActivityForResult(GalleryContent,0);
}
});
//视频必须内存不足或需要在上传前进行压缩。。。
btnPickVideo.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
Intent gallerycontent=新意图(Intent.ACTION\u PICK,
MediaStore.Video.Media.EXTERNAL\u CONTENT\u URI);
startActivityForResult(GalleryContent,1);
}
});
//注意:这是自动生成的,用于实现应用程序索引API。
//看https://g.co/AppIndexing/AndroidStudio 了解更多信息。
client2=new-GoogleApiClient.Builder(this.addApi(AppIndex.API).build();
}
@凌驾
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
super.onActivityResult(请求代码、结果代码、数据);
试一试{
//拾取图像时
if(requestCode==0&&resultCode==RESULT\u确定&&null!=数据){
//从数据中获取图像
Uri selectedImage=data.getData();
字符串[]filePathColumn={MediaStore.Images.Media.DATA};
Cursor Cursor=getContentResolver().query(selectedImage,filePathColumn,null,null);
断言游标!=null;
cursor.moveToFirst();
int columnIndex=cursor.getColumnIndex(filePathColumn[0]);
mediaPath=cursor.getString(columnIndex);
//在ImageView中设置图像以预览媒体
setImageBitmap(BitmapFactory.decodeFile(mediaPath));
cursor.close();
}//拾取视频时
else if(requestCode==1&&resultCode==RESULT\u OK&&null!=数据){
//从数据中获取视频
Uri selectedVideo=data.getData();
String[]filePathColumn={MediaStore.Video.Media.DATA};
Cursor Cursor=getContentResolver().query(selectedVideo,filePathColumn,null,null);
断言游标!=null;
cursor.moveToFirst();
int columnIndex=cursor.getColumnIndex(filePathColumn[0]);
mediaPath=cursor.getString(columnIndex);
//在ImageView中设置视频缩略图以预览媒体
setImageBitmap(getThumbnailPathForLocalFile(MainActivity.this,selectedVideo));
cursor.close();
}否则{
Toast.makeText(这是“您还没有选择图像/视频”,Toast.LENGTH_LONG.show();
}
}捕获(例外e){
Toast.makeText(这是“出错了”,Toast.LENGTH_LONG.show();
}
}
//为所选图像提供缩略图
公共位图getThumbnailPathForLocalFile(活动上下文,Uri文件Uri){
long fileId=getFileId(上下文,fileUri);
返回MediaStore.Video.Thumbnails.getThumbnail(context.getContentResolver(),
fileId,MediaStore.Video.Thumbnails.MICRO_KIND,null);
}
//获取选定的文件ID
公共长getFileId(活动上下文,Uri fileUri){
Cursor Cursor=context.managedQuery(fileUri,mediaColumns,null,null);
if(cursor.moveToFirst()){
int columnIndex=cursor.getColumnIndexOrThrow(MediaStore.Video.Media.\u ID);
返回cursor.getInt(columnIndex);
}
返回0;
}
//上传图像/视频
私有void上传文件(){
progressDialog.show();
//Map用于使用okhttp3.RequestBody对文件进行多部分处理
Map Map=newhashmap();
文件文件=新文件(mediaPath);
RequestBody RequestBody=RequestBody.create(MediaType.parse(“*/*”),文件);
map.put(“fileContent0\”文件名=\“”+file.getName()+“\”,requestBody);
ApiConfig getResponse=AppConfig.getReformation().create(ApiConfig.class);
Call Call=getResponse.upload(令牌、映射);
call.enqueue(新回调(){
@凌驾
公共void onResponse(调用、响应){
ServerResponse ServerResponse=response.body();
public class ServerResponse {
// variable name should be same as in the json response from php
@SerializedName("success")
boolean success;
@SerializedName("message")
String message;
public String getMessage() {
return message;
}
public boolean getSuccess() {
return success;
}
}
public class MainActivity extends AppCompatActivity {
Button btnUpload, btnPickImage, btnPickVideo;
String mediaPath;
ImageView imgView;
String[] mediaColumns = {MediaStore.Video.Media._ID};
ProgressDialog progressDialog;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client2;
@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);
btnPickVideo = (Button) findViewById(R.id.pick_vdo);
imgView = (ImageView) findViewById(R.id.preview);
btnUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
uploadFile();
}
});
btnPickImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, 0);
}
});
// Video must be low in Memory or need to be compressed before uploading...
btnPickVideo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, 1);
}
});
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client2 = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
@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
imgView.setImageBitmap(BitmapFactory.decodeFile(mediaPath));
cursor.close();
} // When an Video is picked
else if (requestCode == 1 && resultCode == RESULT_OK && null != data) {
// Get the Video from data
Uri selectedVideo = data.getData();
String[] filePathColumn = {MediaStore.Video.Media.DATA};
Cursor cursor = getContentResolver().query(selectedVideo, filePathColumn, null, null, null);
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mediaPath = cursor.getString(columnIndex);
// Set the Video Thumb in ImageView Previewing the Media
imgView.setImageBitmap(getThumbnailPathForLocalFile(MainActivity.this, selectedVideo));
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();
}
}
// Providing Thumbnail For Selected Image
public Bitmap getThumbnailPathForLocalFile(Activity context, Uri fileUri) {
long fileId = getFileId(context, fileUri);
return MediaStore.Video.Thumbnails.getThumbnail(context.getContentResolver(),
fileId, MediaStore.Video.Thumbnails.MICRO_KIND, null);
}
// Getting Selected File ID
public long getFileId(Activity context, Uri fileUri) {
Cursor cursor = context.managedQuery(fileUri, mediaColumns, null, null, null);
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID);
return cursor.getInt(columnIndex);
}
return 0;
}
// Uploading Image/Video
private void uploadFile() {
progressDialog.show();
// Map is used to multipart the file using okhttp3.RequestBody
Map<String, RequestBody> map = new HashMap<>();
File file = new File(mediaPath);
RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
map.put("fileContent0\"; filename=\"" + file.getName() + "\"", requestBody);
ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
Call<ServerResponse> call = getResponse.upload(token, map);
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()) {
Log.e("Response", serverResponse.getMessage());
Toast.makeText(getApplicationContext(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
} else {
Log.e("Response", serverResponse.getMessage());
Toast.makeText(getApplicationContext(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
Log.v("Response", serverResponse.toString());
}
progressDialog.dismiss();
}
@Override
public void onFailure(Call<ServerResponse> call, Throwable t) {
Log.e("Throwable", t.toString());
}
});
}
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client2.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://com.delaroystudios.androidupload/http/host/path")
);
AppIndex.AppIndexApi.start(client2, viewAction);
}
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://com.delaroystudios.androidupload/http/host/path")
);
AppIndex.AppIndexApi.end(client2, viewAction);
client2.disconnect();
}
}
HashMap<String, String> login_params = new HashMap<String, String>();
login_params.put("fileCount", "1");
login_params.put("id","1743");
login_params.put("fileType", "SAMPLE");
login_params.put("platform", "Android");
login_params.put("externalID", "portpolio");
@Multipart
@POST("upload")
Call<ResponseBody> uploadFileWithPartMap(
@PartMap() Map<String, RequestBody> partMap,
@Part MultipartBody.Part file);
MultipartBody.Part body = prepareFilePart("photo", fileUri);
// create a map of data to pass along
RequestBody token= RequestBody.create(
MediaType.parse(MULTIPART_FORM_DATA), "token_string");
HashMap<String, RequestBody> map = new HashMap<>();
map.put("token", token);
-----------------
private MultipartBody.Part prepareFilePart(String partName, Uri fileUri) {
// https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
// use the FileUtils to get the actual file by uri
File file = FileUtils.getFile(this, fileUri);
// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(MediaType.parse(MULTIPART_FORM_DATA), file);
// MultipartBody.Part is used to send also the actual file name
return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
}
// finally, execute the request
Call<ResponseBody> call = service.uploadFileWithPartMap(map, body);
call.enqueue(...);