i am trying to upload image to parse server
but it return
https://parsefiles.back4app.com/ehUKQVObBspFk0MBFNSSg3MwLJofpeoFtDhQNIgS/2f345485e2e5cc757c80cfdacf138871_hello.png
whitch contains image cant be displayed because it contain error
it success on uploading image but image is corrupted
note : when i use same code to upload pdf or mp3 files it works well
val response = client.post<HttpResponse>("https://encyriptionapp.b4a.io/parse/files/hello.png") {
headers.append("X-Parse-Application-Id", PublicData.Application_Id)
headers.append("X-Parse-REST-API-Key", PublicData.REST_API_Key)
body = MultiPartFormDataContent(
formData {
append("file", file/*bytes*/, Headers.build {
append(HttpHeaders.ContentType, "image/png")
})
}
)
}
Related
I'm trying to upload an image to an http server that supposedly accepts files in "the standard way", whatever that means. I've combined a bunch of examples from the Internet, each of which does a tiny part of what I want, into this solution.
'srcBitmap' is a byteArray containing the JPG data.
val response: HttpResponse = httpClient.submitFormWithBinaryData(
url = URLUploadFile,
formData = formData {
append("bitmapName", "image.jpg")
append("image", srcBitmap, Headers.build {
append(HttpHeaders.ContentType, "image/jpg")
append(HttpHeaders.ContentDisposition, "filename=image.jpg")
})
},
block = {
headers {
append(HttpHeaders.ContentType, contentTypeString)
append(HttpHeaders.CacheControl, "no-cache")
append("my-app-authtoken", PREFKEY_AUTHTOKEN)
append("my-app-id", PREFKEY_USERID)
}
contentType(ContentType.Application.Json)
body = jsonBody.toString()
})
The main "body" part is some json that gets passed in the 'block' parameter. This data is arriving safely as intended.
But the binary data of the image itself is either not showing up on the server side, or is being ignored by the server because I don't have some "key" value set appropriately.
Is this the correct way to upload a file using Ktor? And if not, what am I doing wrong?
The second append call is a correct way of sending a part with the name image and the filename image.jpg. The problem is that you can't send both application/json and multipart/form-data content in one request.
Actually yours is a correct way, I was facing the same problem with my back-end guy that he receives my request as a byteArray file and couldn't recognized. So what I did was specify the files directly to the body instead of using submitFormWithBinaryData, as below..
'srcBitmap' is a byteArray containing the JPG data.
httpClient.post<RESPONSE>(URL) {
headers {
append(HttpHeaders.Accept, ContentType.Application.Json)
}
body = MultiPartFormDataContent(
formData {
this.append(FormPart("bitmapName", "image.jpg"))
this.appendInput(
key = "image",
headers = Headers.build {
append(
HttpHeaders.ContentDisposition,
"filename=image.jpg"
)
},
) { buildPacket { writeFully(srcBitmap) } }
}
)
}
I'm uploading multiple images to Firebase-Storage.
The problem is if i try to upload 5 images. 2/5 images gets uploaded and I kill the app the uninstall it without reopening it then the two images gets uploaded to firebase storage but the other 3 didn't. And the way I'm storing "download url" is like if all the 5 images gets uploaded then store the url with other data to Firestore and if it fails then don't store download url which means that other data won't get uploaded to Firestore.
This is the function I use to upload multiple images to database.
private fun uploadImages() {
// to store mutliple url's
val imagesUrl = ArrayList<String>()
// mUriImagesList is an arraylist of images
if (mUriImagesList.isNotEmpty()) {
for (image in mUriImagesList) {
// ref = some storage path //
val uploadTask = ref.putFile(image)
val urlTask = uploadTask.continueWithTask { task ->
if(!task.isSuccessful) {
task.exception?.let {
throw it
}
}
ref.downloadUrl
}.addOnCompleteListener { task ->
val downloadUri = task.result
imagesUrl.add(downloadUri.toString())
if(imagesUrl.size == mUriImagesList.size) {
// some other data which will uploaded to firestore if all the images get uploaded to storage
uploadMomentData(imagesUrl)
}
} else {
Log.w(NEW_FRAGMENT_TAG, "Task FAILED")
}
}
}
}
}
Is there any way to delete those 2 images from the storage if all the images failed to upload? - I thought to write a cloud function but what will be the condition? As there is no way to determine the data uploaded to Firebase-storage is not associated in anyway to firestore(by download url).
I'm using nativescript-imagepicker plugin to select images from phone gallery. One of the things this plugin allows me to get, is the path to the file.
I need to be able to upload this selected file to a server, using form data. For that i need to create a file object first.
How can i use a file path, to create a file object?
For uploading images from the photo gallery I would highly suggest using Nativescsript background http. To upload the images to the server you will have to save them within the app so that they can be uploaded. I followed the example shown here Upload example.
Once you have saved the images locally if you want additional data you will need to use multipartUpload and construct a request that would look something like this.
let BackgroundHTTP = require('nativescript-background-http')
let session = BackgroundHTTP.session('some unique session id')
let request: {
url: 'your.url.to/upload/images',
method: 'POST',
headers: {
'Content-Type': 'application/octet-stream'
}
description: 'Uploading local images to the server'
}
//photos should have at least the filename from when you saved it locally.
let params = []
photos.forEach(photo => {
params.push({name: photo.name, filename: photo.filename, value: 'ANY STRING DATA YOU NEED'})
}
let task = session.multipartUpload(params, request)
task.on('progress', evt => {
console.log('upload progress: ' + ((evt.currentBytes / evt.totalBytes) * 100).toFixed(1) + '%')
}
task.on('error', evt => {
console.log('upload error')
console.log(evt)
}
task.on('complete', evt => {
//this does not mean the server had a positive response
//but the images hit the server.
// use evt.responseCode to determine the status of request
console.log('upload complete, status: ' + evt.responseCode)
}
I have this web service
Url: http://menatservice.menatbb.com/MenaServiceCommon.svc/TestUploadImage
Form Data:
ListId : 10
ListType : 1
MenaImage: >> put any image
I tried
val formData = listOf("ListId" to moduleId, "ListType" to moduleType,
"MenaImage" to listOf{images[0].file.inputStream().readBytes()})
this#UploadImageRequest.data1 = images[0].file.readBytes()
return Constants.TestUploadImage.httpUpload(Method.POST, formData)
but I got 400 bad request error while in Postman it is working as the image below
what should I do to make it work by Fuel library?
I want to convert and image into base64 format and then upload that onto the server but the base64 string is so large that it gives me error on web that parameter not received.Any idea to send the complete string to the server using the below webservice? Here is below service that i tried.
var xhrAddclient = Titanium.Network.createHTTPClient();
xhrAddclient.open('POST', webservice_url);
xhrAddclient.send({
method : "addclient",
image : base64string,
});
xhrAddclient.setTimeout(10000);
xhrAddclient.onerror = function() {
showAlertBox('Service timed out. Please try again.');
};
xhrAddclient.onload = function() {
showAlertBox("Client added successfully.");
};
Check here: http://www.smokycogs.com/blog/titanium-tutorial-how-to-upload-a-file-to-a-server/
and here: https://wiki.appcelerator.org/display/guides/File+Uploads+and+Downloads#FileUploadsandDownloads-Fileupload
or just:
xhr.setRequestHeader("Content-type", "multipart/form-data");
xhr.send(file);