I am trying to upload a video file using multipart by retrofit and I get the following error in response
Response{protocol=http/1.1, code=405, message=Method Not Allowed, url=serverurl/Upload/Videos/}
This is my code for file upload
void uploadVideo(String videoPath) {
dialog.show();
File videoFile = new File(videoPath);
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), videoPath);
MultipartBody.Part vFile = MultipartBody.Part.createFormData("file", videoFile.getName(), requestFile);
apiCall.uploadVideoToServer(presenter.getUserInfo().getUploadVideoPath(), vFile).enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
dialog.dismiss();
}
#Override
public void onFailure(Call<String> call, Throwable t) {
dialog.dismiss();
}
});
}
This is the path I am uploading the file to
http://serverurl.com/Upload/Videos/
Can someone tell me whats wrong with my code?
Retrofir API interface
#Multipart
#POST
Call<String> uploadVideoToServer(#Url String url, #Part MultipartBody.Part video);
in your api service interface :
#Multipart
#POST("Upload/Videos") // *** DONT FORGET UR END POINT HERE ***
Call<urmodel> uploadVideoToServer(#PartMap Map<String, RequestBody> map);
and write a method to upload ur video file like this :
private void uploadVideoToServer(String path) {
File videoFile = new File(path);
if (videoFile.exists()) {
//create request body
Map<String, RequestBody> map = new HashMap<>();
RequestBody requestBody = RequestBody.create(MediaType.parse("video/*"), videoFile);
map.put("video\"; filename=\"" + videoFile.getName() + "\"", requestBody);
//make call
Call<urmodel> call = mTService.uploadVideoToServer(map);
call.enqueue(new Callback<urmodel>() {
#Override
public void onResponse(Call<urmodel> call, Response<urmodel> response) {
if (response.isSuccess()) {
// DO SOMETHING
} else {
// DO SOMETHING
}
}
#Override
public void onFailure(Call<urmodel> call, Throwable t) {
//occur when fail to deserialize || no network connection || server unavailable
Toast.makeText(getBaseContext(), "Fail it >> " + t.getMessage(), Toast.LENGTH_LONG).show();
}
});
} else {
Toast.makeText(getBaseContext(), "can not upload file since the file is not exist :|", Toast.LENGTH_SHORT).show();
}
}
Related
I am trying to upload files from android device to the server using retrofit.
But every time, it results with no in the console.
FilesApi.java:
public interface FilesApi {
#Multipart
#POST("file")
Call<String> storeFile(#Part MultipartBody.Part file);
}
In MainActivity.java:
private void uploadFile(){
RequestBody requestFile= RequestBody.create(MediaType.parse("multipart/form-data"),file);
MultipartBody.Part body =
MultipartBody.Part.createFormData("file", file.getName(), requestFile);
//RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),file);
FilesApi api = RetrofitService.createService(FilesApi.class);
api.storeFile(body).enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
Log.d(TAG, "onResponse: "+response.body());
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.d(TAG, "onFailure: "+t);
}
});
}
PHP code:
<?php
if(isset($_FILES['file']))
{
echo "YESS";
}
else
{
echo "no";
}
?>
The Filename should be the same on the Retrofit Parameter as well on the Server Key.
Please refer this link for complete guidance.
https://www.simplifiedcoding.net/retrofit-upload-file-tutorial/
My file picked from gallery and set to imageview but after click on upload button not able upload my file on server
I am using local host,my server side code is correct because image is uploading via postman
File file = new File(mediaPath);
// parsing media type file
RequestBody requestBody1 = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part fileToUpload1 = MultipartBody.Part.createFormData("input_img", file.getName(), requestBody1);
ServiceApi call = ClientApi.getData().create(ServiceApi.class);
Call<ResponseData> data = call.update(fileToUpload1);
data.enqueue(new Callback<ResponseData>()
{
#Override
public void onResponse(Call<ResponseData> call, Response<ResponseData> response)
{
ResponseData data = response.body();
if(data.getStatus().equals("true"))
{
Toast.makeText(getApplicationContext(), "yes",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "no",Toast.LENGTH_SHORT).show();
}
// Log.d("data",data.getUpdateUserData().toString());
}
#Override
public void onFailure(Call<ResponseData> call, Throwable t)
{
Toast.makeText(getApplicationContext(), "Please check once",Toast.LENGTH_SHORT).show();
}
});
private void saveImageToServer(final String savedpath) {
showLoader();
NetworkUtil.checkInternetConnection(DetailActiveSRActivity.this, new NetworkUtil.NetworkStatusListener() {
#Override
public void onNetworkAvailable() {
File file = new File(savedpath);
// RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), savedpath);
RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);
Log.e(TAG, "onNetworkAvailable: requestFIle " + savedpath+"\n"+" file "+file);
MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
Log.e(TAG, "onNetworkAvailable: body " + body);
RequestBody reqUserId = RequestBody.create(MediaType.parse("text/plain"), userId);
//RequestBody reqImageType =RequestBody.create(MediaType.parse("text/plain"), "1");
Call<SaveImageResponseModel> responseCall = mService.saveImages(body, reqUserId);
responseCall.enqueue(new Callback<SaveImageResponseModel>() {
#Override
public void onResponse(Call<SaveImageResponseModel> call, retrofit2.Response<SaveImageResponseModel> response) {
hideLoader();
if (response != null) {
SaveImageResponseModel apiResponse = response.body();
if (apiResponse != null && apiResponse.getStatus()) {
Log.e(TAG, "onRequestSuccess: " + apiResponse);
} else {
Toast.makeText(DetailActiveSRActivity.this, getString(R.string.noDataError), Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(DetailActiveSRActivity.this, getString(R.string.noDataError), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<SaveImageResponseModel> call, Throwable t) {
hideLoader();
}
});
}
#Override
public void onNetworkNotAvailable() {
Toast.makeText(DetailActiveSRActivity.this, getString(R.string.noNetworkMessage), Toast.LENGTH_SHORT).show();
hideLoader();
}
});
}
#Headers({
"authkey: ABCD#123"
})
#Multipart
#POST(UrlUtils.POST_IMAGES)
Call<SaveImageResponseModel> saveImages(#Part MultipartBody.Part file, #Part("userId") RequestBody userId);
First of all, no description, please add a little bit more.
Second:
show what is the content of mService.saveImages(body, reqUserId);
is the HTTP call of POST type?
is the endpoint really working? You should for example try to make call through Postman and you'll see, if it is going through
I am trying to get my Retrofit2 to upload an image to my Flask server, I am not sure why it is not sending the parameter "file" when sending the request.
APIInteface.java
#Multipart
#PUT("api/user/update/")
Call<ResponseBody> UpdateUser(#QueryMap Map<String,String> options,
#Part MultipartBody.Part image, #Part("file") RequestBody file);
MainActivity:
File file = new File(filePath);
Log.d(TAG,"Calling update function");
update(file);
}
}
public void update(File file) {
Log.d(TAG,"I got called, yey!");
ApiInterface apiService = ApiClient.GetAuthClient(token).create(ApiInterface.class);
RequestBody reqFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), reqFile);
RequestBody name = RequestBody.create(MediaType.parse("multipart/form-data"), "upload_test");
data.put("uname",username.getText().toString());
data.put("fname",firstname.getText().toString());
data.put("lname",lastname.getText().toString());
data.put("address",address.getText().toString());
data.put("password",password.getText().toString());
data.put("preferance1",String.valueOf(spinner1.getSelectedItem()));
data.put("preferance2",String.valueOf(spinner2.getSelectedItem()));
data.put("preferance3",String.valueOf(spinner3.getSelectedItem()));
Call<ResponseBody> call = apiService.UpdateUser(data,body,name);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
});
}
I'm sending object in request body, something like that :
{
"title":"test",
"description":"test",
"images":[]
}
#POST("create-data")
Call<JsonObject> publishData(#Body MyObject object);
and it's work fine without the images. From the docs I can find how to upload file to server using MultipartBody.Part, my questions is :
How can I upload multiple images at the same time?
Is it possible to send the images inside the object, or I need to send it separately and how ?
thank you very much.
request success just now with server
I reference the article:
https://futurestud.io/blog/retrofit-2-how-to-upload-files-to-server
#Multipart
#POST("uploadHeadPic")
Call<UploadHeadPicResponseModel> uploadHeadPic(#Part MultipartBody.Part file, #Part("json") RequestBody json);
public void doUploadHeadPic(#NonNull String filePath) {
if (!MNetworkUtil.isNetworkAvailable()) {
MToastUtil.show("网络不能连接");
return;
}
File file = new File(filePath);
String json = new Gson().toJson(new UploadHeadPicRequestModel());
if (!file.exists()) {
MToastUtil.show("文件不存在");
return;
}
progressDialog.show();
avatarSimpleDraweeView.setEnabled(false);
MApiManager.getService().uploadHeadPic(
MultipartBody.Part.createFormData("file", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file)),
RequestBody.create(MediaType.parse("multipart/form-data"), json))
.enqueue(new OnRetrofitCallbackListener<UploadHeadPicResponseModel>(mActivity) {
#Override
public void onSuccess(UploadHeadPicResponseModel responseModel) {
progressDialog.dismiss();
avatarSimpleDraweeView.setEnabled(true);
if (responseModel != null) {
String serverAvatarUrl = responseModel.data.headPicPath;
if (!TextUtils.isEmpty(serverAvatarUrl)) {
UserModel userModel = MUserManager.getInstance().getUser();
if (userModel != null) {
userModel.setAvatarUrl(serverAvatarUrl);
MUserManager.getInstance().updateOrInsertUserInfo(userModel);
MToastUtil.show("上传头像成功");
}
}
}
}
#Override
public void onFailure(int status, String failureMsg) {
progressDialog.dismiss();
avatarSimpleDraweeView.setEnabled(true);
MToastUtil.show((TextUtils.isEmpty(failureMsg) ? "上传失败" : failureMsg) + " : " + status);
}
});
}
update for multi files
may be this could help , I did not try
#Multipart
#POST("uploadHeadPic")
Call<UploadHeadPicResponseModel> uploadHeadPic(#Part MultipartBody.Part file0, #Part MultipartBody.Part file1, #Part("json") RequestBody json);
public void doUploadHeadPic(#NonNull String filePath) {
MApiManager.getService().uploadHeadPic(
MultipartBody.Part.createFormData("file0", file0.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file0)),
MultipartBody.Part.createFormData("file1", file1.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file1)),
RequestBody.create(MediaType.parse("multipart/form-data"), json))
.enqueue(new OnRetrofitCallbackListener<UploadHeadPicResponseModel>(mActivity) {
#Override
public void onSuccess(UploadHeadPicResponseModel responseModel) {
}
#Override
public void onFailure(int status, String failureMsg) {
}
});
}
In my case (uploading to server built with Spring) I needed to change MediaType for RequestBody:
RequestBody.create(MediaType.parse("application/json"), json)
RequestBody.create(MediaType.parse("image/jpg"), file)