我想将文件(Image)和一些参数发送到服务器,然后我的php脚本将它们发送到数据库。我已经尝试过了。我的文件已经上传到服务器中,文件名已经上传到数据库中,但参数不包括在内。
我会展示我的代码。我希望你能帮助我。
ApiService.java
public interface ApiService {
/*
Retrofit get annotation with our URL
And our method that will return us the List of Contacts
*/
@Multipart
@POST("upload(Testing).php")
Call<Result> uploadImage(@Part MultipartBody.Part file,
@Part("id_user") RequestBody idUser,
@Part("p_id_doc_proj") RequestBody p_id_doc_proj,
@Part("id_doc_type") RequestBody id_doc_type,
@Part("id_project") RequestBody idProject);
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
/**
* Permission List
*/
private static final String[] PERMISSIONS_READ_STORAGE = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE};
/**
* Context Variables
*/
Context mContext;
/**
* Views
*/
View parentView;
ImageView imageView;
TextView textView;
/**
* Image path to send
*/
String imagePath;
String idUser = "4";
String p_id_doc_proj = "90";
String id_project = "16";
String id_doc_type = "1";
/**
*
*/
PermissionsChecker checker;
/**
*
*/
Toolbar toolbar;
/**
* @param savedInstanceState
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = getApplicationContext();
/**
* Parent View
*/
parentView = findViewById(R.id.parentView);
/**
* Permission Checker Initialized
*/
checker = new PermissionsChecker(this);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
textView = (TextView) findViewById(R.id.textView);
imageView = (ImageView) findViewById(R.id.imageView);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
assert fab != null;
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!TextUtils.isEmpty(imagePath)) {
/**
* Uploading AsyncTask
*/
if (InternetConnection.checkConnection(mContext)) {
/******************Retrofit***************/
uploadImage();
} else {
Snackbar.make(parentView, R.string.string_internet_connection_warning, Snackbar.LENGTH_INDEFINITE).show();
}
} else {
Snackbar.make(parentView, R.string.string_message_to_attach_file, Snackbar.LENGTH_INDEFINITE).show();
}
}
});
}
/**
* Upload Image Client Code
*/
private void uploadImage() {
/**
* Progressbar to Display if you need
*/
final ProgressDialog progressDialog;
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage(getString(R.string.string_title_upload_progressbar_));
progressDialog.show();
progressDialog.setCancelable(false);
//Create Upload Server Client
final ApiService service = RetroClient.getApiService();
//File creating from selected URL
File url = new File(imagePath);
// create RequestBody instance from file
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), url);
RequestBody userID = RequestBody.create(okhttp3.MultipartBody.FORM, idUser);
RequestBody idDocProj = RequestBody.create(okhttp3.MultipartBody.FORM, p_id_doc_proj);
RequestBody idProj = RequestBody.create(okhttp3.MultipartBody.FORM, id_project);
RequestBody idDocType = RequestBody.create(okhttp3.MultipartBody.FORM, id_doc_type);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
MultipartBody.Part.createFormData("uploaded_file", url.getName(), requestFile);
final Call<Result> resultCall = service.uploadImage(body, userID, idDocProj, idDocType, idProj);
// finally, execute the request
resultCall.enqueue(new Callback<Result>() {
@Override
public void onResponse(Call<Result> call, Response<Result> response) {
progressDialog.dismiss();
//Snackbar.make(parentView, response.toString(), Snackbar.LENGTH_LONG).show();
Snackbar.make(parentView, response.body().getResult().toString(), Snackbar.LENGTH_LONG).show();
// Response Success or Fail
/*if (response.isSuccessful()) {
if (response.body().getResult().equals("success")) {
imagePath = "";
textView.setVisibility(View.VISIBLE);
imageView.setVisibility(View.INVISIBLE);
//Snackbar.make(parentView, response.body().getResult().toString(), Snackbar.LENGTH_LONG).show();
}
//else
//Snackbar.make(parentView, response.body().getResult().toString(), Snackbar.LENGTH_LONG).show();
} else {
//Snackbar.make(parentView, response.body().getResult().toString(), Snackbar.LENGTH_LONG).show();
}*/
/**
* Update Views
*/
}
@Override
public void onFailure(Call<Result> call, Throwable t) {
Snackbar.make(parentView, R.string.string_upload_fail, Snackbar.LENGTH_LONG).show();
progressDialog.dismiss();
}
});
}
/**
* Showing Image Picker
*/
public void showImagePopup(View view) {
if (checker.lacksPermissions(PERMISSIONS_READ_STORAGE)) {
startPermissionsActivity(PERMISSIONS_READ_STORAGE);
} else {
// File System.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_PICK);
// Chooser of file system options.
final Intent chooserIntent = Intent.createChooser(galleryIntent, getString(R.string.string_choose_image));
startActivityForResult(chooserIntent, 1010);
}
}
/***
* OnResult of Image Picked
*
* @param requestCode
* @param resultCode
* @param data
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == 1010) {
if (data == null) {
Snackbar.make(parentView, R.string.string_unable_to_pick_image, Snackbar.LENGTH_INDEFINITE).show();
return;
}
Uri selectedImageUri = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImageUri, filePathColumn, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imagePath = cursor.getString(columnIndex);
Picasso.with(mContext).load(new File(imagePath))
.into(imageView);
Snackbar.make(parentView, R.string.string_reselect, Snackbar.LENGTH_LONG).show();
cursor.close();
textView.setVisibility(View.GONE);
imageView.setVisibility(View.VISIBLE);
} else {
textView.setVisibility(View.VISIBLE);
imageView.setVisibility(View.GONE);
Snackbar.make(parentView, R.string.string_unable_to_load_image, Snackbar.LENGTH_LONG).show();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void startPermissionsActivity(String[] permission) {
PermissionsActivity.startActivityForResult(this, 0, permission);
}
}
RetroClient.java
public class RetroClient {
/**
* Upload URL of your folder with php file name...
* You will find this file in php_upload folder in this project
* You can copy that folder and paste in your htdocs folder...
*/
private static final String ROOT_URL = "http://172.xx.x.xxx/Upload/";
public RetroClient() {
}
/**
* Get Retro Client
*
* @return JSON Object
*/
private static Retrofit getRetroClient() {
return new Retrofit.Builder()
.baseUrl(ROOT_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
public static ApiService getApiService() {
return getRetroClient().create(ApiService.class);
}
}
由于
更新
这是我的服务器端代码
<?php
$file_path = "";
$id_project = $_REQUEST["id_project"];
$p_id_doc_proj = $_REQUEST["p_id_doc_proj"];
$id_doc_type = $_REQUEST["id_doc_type"];
$id_user = $_REQUEST["id_user"];
$url1 = "http://172.x.x.x/Upload_Ruben/";
$url2 = $file_path.basename($_FILES['uploaded_file']['name']);
$url = $url1.$url2;
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $url2)){
$ws = "http://172.x.x.x:xxxx/UploadImage/$id_project/$p_id_doc_proj/$id_doc_type/$id_user/$url";
$opts = array('http'=>array('header'=>'Content-type: application/x-www-form-urlencoded'));
$context = stream_context_create($opts);
$arrayLog = array();
$data1 = file_get_contents($ws, false, $context);
$result = json_encode($data1);
}else{
$result = array("result" => "error");
}
?>
答案 0 :(得分:0)
以下是发送方式
@Multipart
@POST("/edit_user_profile")
Call<String> editProfileServerCall(@Part("access_token") RequestBody
accessToken, @Part("user_name") RequestBody name, @Part("user_mobile")
RequestBody userPhone, @Part("user_email") RequestBody email, @Part
MultipartBody.Part image);
以下是您的称呼方式 -
public void editProfileServerCall(final Context context, String name, String phoneNumber, File image, String email, final ProfilePresenter.EditProfilePresenter editProfilePresenter) {
editProfilePresenter.showLoader();
RequestBody userName = RequestBody.create(MediaType.parse("text/plain"), name);
RequestBody userPhone = RequestBody.create(MediaType.parse("text/plain"), phoneNumber);
RequestBody userEmail = RequestBody.create(MediaType.parse("text/plain"), email);
RequestBody accessToken = RequestBody.create(MediaType.parse("text/plain"), Constants.userData.getAccessToken());
RequestBody file = RequestBody.create(MediaType.parse("image/jpg"), image);
MultipartBody.Part userImage = MultipartBody.Part.createFormData("user_image", image.getName(), file);
RestClient.getApiService().editProfileServerCall(accessToken, userName, userPhone, userEmail, userImage).enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
editProfilePresenter.hideLoader();
Log.e("edit_profile_response",""+ response.body().toString());
try {
JSONObject object = new JSONObject(response.body().toString());
if (object.getInt("is_error") == 0) {
if (object.has("user_profile")) {
CommonParser.parseProfileData(context, object.getJSONObject("user_profile"));
editProfilePresenter.success();
}
} else {
editProfilePresenter.error(Constants.popupResponseObject.getJSONObject("" + object.getInt("flag")).getString("text"));
}
} catch (JSONException e) {
e.printStackTrace();
editProfilePresenter.error(Constants.serverError);
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
editProfilePresenter.hideLoader();
editProfilePresenter.error(Constants.serverError);
}
});
}