Upload image server using multipart in android - android

Upload image server using multipart in android. Here i have used this url
public static final String UPLOAD_URL = "http://abcds.com/clients/cupidapi/uploadimg";
Here i have used multipart to upload image in Mysql database server. When i try to upload image on server, it shows notification in my device saying "Upload successfully" but there is no image record uploaded in database.
public void uploadMultipart() {
//getting the actual path of the image
String path = getPath(filePath);
Log.e(TAG,"PATH---------->"+path);
//Uploading code
try {
String uploadId = UUID.randomUUID().toString();
Log.e(TAG,"UPLOADID-------->"+uploadId);
//Creating a multi part request
new MultipartUploadRequest(this, uploadId,UPLOAD_URL)
.addFileToUpload( "image",path) //Adding file
.addParameter("name", name) //Adding text parameter to the request
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
Log.e(TAG,"URL----->"+path);
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
Log.e(TAG,"GETMESSAGE"+exc.getMessage());
}
}
the content I get logged looks like this:
03-20 13:42:28.316 12069-12089/com.example.uploadimageserver E/[DRVB][EXT][UTIL]: disp_only_chk: DRVB CHECK DISP PROCESS DONE ! (1/0x2f/0x30/0x2e)
03-20 13:42:28.316 12069-12089/com.example.uploadimageserver E/[DRVB][EXT][UTIL]: disp_only_chk: DRVB CHECK DISP PROCESS DONE ! (0/0/0)
03-20 13:46:44.656 12069-12069/com.example.uploadimageserver E/MainActivity: PATH---------->/storage/emulated/0/Pictures/Instagram/IMG_20190218_082042_666.jpg
03-20 13:46:44.691 12069-12069/com.example.uploadimageserver E/MainActivity: UPLOADID-------->35020ace-11aa-40cc-b0f4-50ec2879b9bd
03-20 13:46:44.745 12069-12069/com.example.uploadimageserver E/MainActivity: URL----->/storage/emulated/0/Pictures/Instagram/IMG_20190218_082042_666.jpg
Here my server code:
private function uploadimg(){
$currentDir = getcwd();
$uploadDirectory = "profile/";
$errors = []; // Store all foreseen and unforseen errors here
$fileExtensions = ['jpeg','jpg','png','gif']; // Get all the file extensions
$userid =$_POST['user_id'];
$fileName = $_FILES['images']['name'];
$fileSize = $_FILES['images']['size'];
$fileTmpName = $_FILES['images']['tmp_name'];
$fileType = $_FILES['images']['type'];
$fileExtension = strtolower(end(explode('.',$fileName)));
$uploadPath = $currentDir . $uploadDirectory . basename($fileName);
$uploadPath = $uploadDirectory . basename($fileName);
$imgurl="https://abcds.com/clients/cupidapi/".$uploadDirectory.$fileName ;
if (isset($_POST['name'])) {
if (! in_array($fileExtension,$fileExtensions)) {
$errors[] = "This file extension is not allowed. Please upload a JPEG or PNG file";
}
if ($fileSize > 2000000) {
$errors[] = "This file is more than 2MB. Sorry, it has to be less than or equal to 2MB";
}
if (empty($errors)) {
$didUpload = move_uploaded_file($fileTmpName, $uploadPath);
if ($didUpload) {
$success[] = "profile upload successfuly";
$sql ="INSERT INTO db_images(image_path,user_id) VALUES('$imgurl','$userid')";
$res=mysql_query($sql);
} else {
$errors[] = "An error occurred somewhere. Try again or contact the admin";
}
} else {
foreach ($errors as $error) {
$errors[] = $error . "These are the errors" . "\n";
}
}
}else{
$re="inserting problem....";
print(json_encode($re));
}
if(!$res)
{
$re="inserting problem....";
print(json_encode($re));
}
else{
$re="inserting success....";
print(json_encode($success));
}
}

Try to this example it is very good and easy to upload image file without any stretch image.
// Upload File
def uploadServiceVersion = "3.4.2"
implementation "net.gotev:uploadservice:$uploadServiceVersion"
Goto GitHub then see the code
https://github.com/gotev/android-upload-service/wiki/Setup

Related

How to send image file to server - Kotlin using Fuel

I have a problem when attempting to use Fuel to send image to my server.
I am trying to use the Fuel.upload method.
Fuel.upload(urlfile).source { request, url ->
File(photopath)
}.responseString { request, response, result ->
}
the image is like : /storage/emulated/0/Android/data/fr.tais.riodi/files/Pictures/MyPicture4945313277123614993.jpg
$target_dir = "images/";
$target_file_name = $target_dir .basename($_FILES["file"]["name"]);
$response = array();
// Check if image file is a actual image or fake image
if (isset($_FILES["file"]))
{
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file_name))
{
$success = true;
$message = "Successfully Uploaded";
}
else
{
$success = false;
$message = "Error while uploading";
}
}
else
{
$success = false;
$message = "Required Field Missing";
}
$response["success"] = $success;
$response["message"] = $message;
echo json_encode($response);
I tried to find an example of this operation. Have you an examples or an idea?
Thanks all

Received Multipart File by Spring is null

I have a File and i want to send it to Spring Backend from Android. After receiving the image at Spring I am changing the name of the Image by Generating the UUID and then uploading it to AWS S3. My problem is i am getting null value as response.
Android Side ->
My Android Upload File Function ->
private void UploadFiles() {
File uploadFile = fileArrayList.get(0);
if (uploadFile != null) {
Log.d(TAG, "UploadFiles: File Name is -> " + uploadFile.getName());
// cropImageRequest.setCropId(uploadFile.getParentFile().getName());
// Parsing any Media type file
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), uploadFile);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part cropImage = MultipartBody.Part.createFormData("cropImage", uploadFile.getName(), requestFile);
Api.uploadCropImage(cropImage, new Callback<BasicResponse>() {
#Override
public void onResponse(Call<BasicResponse> call, Response<BasicResponse> response) {
if (response.body() != null) {
Log.d(TAG, "onResponse: Success" + response.body().getResponse());
}
else{
Log.d(TAG, "onResponse: null Response");
}
}
#Override
public void onFailure(Call<BasicResponse> call, Throwable t) {
Log.d(TAG, "onResponse: Failure");
}
});
}
}
**uploadImageFunction -> **
public static void uploadCropImage(MultipartBody.Part cropImage, Callback<BasicResponse> callback) {
UploadCropImageApi uploadCropImageApi = retrofit.create(UploadCropImageApi.class);
Call<BasicResponse> call = uploadCropImageApi.uploadCropImage(cropImage);
call.enqueue(callback);
}
My Interface ->
public interface UploadCropImageApi {
#Multipart
#POST(UPLOAD_FILE_TO_AWS_URL)
Call<BasicResponse> uploadCropImage(#Part MultipartBody.Part cropImage);
}
This is my Spring File ->
#RequestMapping(value = "/UploadCropImage", method = RequestMethod.POST, consumes = {"multipart/form-data"})
#ResponseBody
public String UploadImage(#RequestBody MultipartFile cropImage,HttpServletRequest request) {
mAmazonClient = AmazonClient.GetAmazonClientInstance();
UUIDUtils uuid = new UUIDUtils();
try {
System.out.println(cropImage);
String KeyName = uuid.GenerateUUID(cropImage.getName());
String Code = mAmazonClient.uploadImage(KeyName, cropImage);
System.out.println(Code);
return Code;
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
return null;
}
}
This Controller is printing following value ->
org.springframework.web.multipart.commons.CommonsMultipartFile#b0b5de0
File Name is -: cropImage
null
My Problem is that as you can see the file sent by Retrofit and received by Spring is not null, I am sending that file via AWS, but it's not uploading the file and returns null as value. But when i use POSTMAN it's easily sending the file to AWS and returns the KeyName.
Okay so i debug a little bit and found out an exception while uploading Image file. and the exception is this -> The filename, directory name, or volume label syntax is incorrect.
Your exception says there is something wrong in your file name. The problem is naming convention as it was uploading file name containing ":" sign and there may be other signs as well which is not accepted by AWS. so, just change file name and separate the names by _(Underscore) sign instead of " "(space), (:) and other signs. This will successfully upload the file to the AWS. Hope it helps.

YouTube video upload showing "Required parameter: part" error for some users

I'm trying to find out why some of our users are getting the error "Required parameter: part" when trying to upload a video into YouTube using YouTube API v3. Below you can see the code that we use for uploading videos. The method params are valid strings that aren't short or too long.
int shareYoutube(#NonNull Uri mediaUri, String mime, String mediaTitle, String postMessage, String accountName)
{
int error = ERR_NO_ERROR;
try {
// Developer tags not supported yet
//https://code.google.com/p/gdata-issues/issues/detail?id=5012
// Authorize the request.
GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(getApplicationContext(), Arrays.asList(YouTubeScopes.YOUTUBE_UPLOAD));
credential.setSelectedAccountName(accountName);
// This object is used to make YouTube Data API requests.
YouTube.Builder builder = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential);
builder.setApplicationName("TEST APP");
YouTube youtube = builder.build();
// Add extra information to the video before uploading.
Video video = new Video();
// set privacy
VideoStatus status = new VideoStatus();
status.setPrivacyStatus("public");
video.setStatus(status);
// Most of the video's metadata is set on the VideoSnippet object.
VideoSnippet snippet = new VideoSnippet();
snippet.setTitle(mediaTitle);
snippet.setDescription(postMessage);
// Film & Animation https://gist.github.com/dgp/1b24bf2961521bd75d6c
snippet.setCategoryId("1");
// Set the keyword tags that you want to associate with the video.
List<String> tags = new ArrayList<>();
tags.add("animation");
tags.add("cartoon");
tags.add("2d animation");
tags.add("drawing");
snippet.setTags(tags);
// Add the completed snippet object to the video resource.
video.setSnippet(snippet);
String fileFormat = "video/*";
InputStreamContent mediaContent = new InputStreamContent(fileFormat, getContentResolver().openInputStream(mediaUri));
// Insert the video. The command sends three arguments. The first
// specifies which information the API request is setting and which
// information the API response should return. The second argument
// is the video resource that contains metadata about the new video.
// The third argument is the actual video content.
YouTube.Videos.Insert videoInsert = youtube.videos().insert("snippet,statistics,status", video, mediaContent);
// Insert to a channel
//videoInsert.setOnBehalfOfContentOwnerChannel();
// Set the upload type and add an event listener.
MediaHttpUploader uploader = videoInsert.getMediaHttpUploader();
// Indicate whether direct media upload is enabled. A value of
// "True" indicates that direct media upload is enabled and that
// the entire media content will be uploaded in a single request.
// A value of "False," which is the default, indicates that the
// request will use the resumable media upload protocol, which
// supports the ability to resume an upload operation after a
// network interruption or other transmission failure, saving
// time and bandwidth in the event of network failures.
uploader.setDirectUploadEnabled(false);
YouTubeCallbackListener callback = new YouTubeCallbackListener();
uploader.setProgressListener(callback);
// Call the API and upload the video.
Video returnedVideo = videoInsert.execute();
synchronized (callback) {
if (!callback.hasCallbackResult()) {
try {
callback.wait();
error = callback.error;
} catch (InterruptedException e) {
e.printStackTrace();
error = ERR_POST_CANCELED;
}
} else {
error = callback.error;
}
}
if (ERR_NO_ERROR == error && null != returnedVideo)
{
Intent notificationIntent = new Intent(
Intent.ACTION_VIEW,
Uri.parse("http://www.youtube.com/watch?v="+returnedVideo.getId()));
mPendingIntent = PendingIntent.getActivity(getBaseContext(), 0, notificationIntent, 0);
}
}
catch (UserRecoverableAuthIOException userRecoverableException)
{
error = ERR_UNABLE_TO_AUTH_ACCOUNT;
try {
GoogleAuthUtil.getTokenWithNotification(
getApplicationContext(), accountName, "oauth2:" + YouTubeScopes.YOUTUBE_UPLOAD, null);
} catch (IOException e) {
} catch (GoogleAuthException e) {
}
} catch (GoogleJsonResponseException e) {
error = ERR_POST_ERROR;
Crashlytics.logException(e);
} catch (IOException e) {
error = ERR_POST_ERROR;
Crashlytics.logException(e);
} catch (Throwable t) {
error = ERR_POST_ERROR;
Crashlytics.logException(t);
}
return error;
}
Error:
400 Bad Request { "errors" : [ { "domain" : "global", "reason" : "required", "message" : "Required parameter: part", "locationType" : "parameter", "location" : "part" } ], "code" : 400, "message" : "Required parameter: part" }
Any thoughts on what could be happening here?
The problem was our proguard script. All we had to do was include the following line to it.
-keep class com.google.api.** { *; }

How to delete already uploaded image file from server?

I created image uploading through a XAMPP server using PHP. But I need to
know how to delete the uploaded image file from Android. How can I do that?
php file(upload) :
<?PHP
if(isset($_POST['image'])){
$now = DateTime::createFromFormat('U.u', microtime(true));
$id = $now->format('YmdHisu');
$upload_folder = "upload/";
$path = "$upload_folder/$id.jpeg";
$image = $_POST['image'];
if(file_put_contents($path, base64_decode($image)) != false){
echo "uploaded_success";
exit;
}
else
{
echo "Sorry, your file is too large.";
echo "upload_failed";
exit;
}
}
else{
echo "image_not_in";
exit;
}
?>
You can get the photo path and delete it in the successful response from the server!
make sure you declare permission in the manifest!
<uses-permission> android:name="android.permission.WRITE_INTERNAL_STORAGE" />
in you code..
PostResponseAsyncTask task = new PostResponseAsyncTask(MainActivity.this, postData, new AsyncResponse() {
#Override
public void processFinish(String s) {
if (s.contains("uploaded_success")) {
File photoDelete = new File(selectedPhoto);
if (photoDelete.exists()) {
if (photoDelete.delete()) {
Log.d("DELETE", "deleted:" + selectedPhoto);
}
}
Toast.makeText(getApplicationContext(), "Image Uploaded Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Error while uploading...", Toast.LENGTH_SHORT).show();
}
}
});
You can delete an image from your server by sending a command from your app (client) to the server asking the server to delete the file from its local storage.
Let's say you set the imageName of your image file to to hashmap to send to the server by:
HashMap<String, String> postData = new HashMap<String, String>();
postData.put("deleteImage", imageName);
and execute it:
task.execute("http://192.168.1.7/news/delete.php");
Now, you just need to see if the value of the deleteImage is set or not (on your server, in the delete.php file) by and delete the file by calling unlink method in PHP:
Delete.php
<?PHP
if(isset($_POST['deleteImage'])){
$imageName = $_POST['deleteImage'];
unlink($imageName) //this deletes the image file
}
?>

how to send body parameter with multipart file upload request usin ion library?

This is the first time ever I am using multi part request to upload data on the server.I am using ion for service hit can you please let me know how can I post my data on the server?
This is my request parameter
jSON Request:
{s_id
note_name
file_name
tag_name
set_date
mark_as_done
clear_reminder
Description
media_name1
media_name2
media_name3
Count = 3 }
Along with it, I have to upload file media1, media2, media2 on same api**. Any help would be greatly appreciated.Thanks
You can't do a JSON body and a Multipart body in one HTTP request.
you can send your json as a parameter :)
// first create your json object
JsonObject object = new JsonObject();
object.addProperty("note_name", "your value goes here");
object.addProperty("description", "your description goes here");
// add other stuffs here
//create list of files to upload
List<Part> files = new ArrayList<>();
for (int i = 1; i <= 3; i++) {
files.add(new FilePart("file" + i, new File("path of file like: storage/image/....")));
}
Ion.with(context)
.load("POST","http://example.com")
.uploadProgress(new ProgressCallback() {
#Override
public void onProgress(long downloaded, long total) {
int percent = (int) (downloaded * 100 / total);
// update your progressbar with this percent if needed
}
})
.addMultipartParts(files)
.setMultipartParameter("json", object.toString()) // your json is here
.asString()
.setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
if (e != null) {
// error: log the message here
return;
}
if (result != null) {
// result is the response of your server
}
}
});
Hope this help you :)

Categories

Resources