How to upload audio file from android to server through .net webservice? - android

We have a web application made in MVC3 which is hosted in Android & Iphone also .Now the android developer is trying to upload an audio file through our method which is written in controller as http post method . They say they are sending the file in form of multipart chunks or byte buffer body . So I took variable of type byte array[] in my method but the type is not coinciding with their datatype . I even tried to keep string , byte , httppostedfilebase types , but still no success . Any help would be appreciated .

Take a look at the VoiceModel open source project for an example of how to save audio using ASP.NET MVC. There is an example project in there called RecordingExample which takes an audio file sent from a VoiceXML browser or Interactive Voice Response (IVR) systems and saves it to the file system. Here is the code that receives the audio file and saves it to disk.
[HttpPost]
public ActionResult SaveRecording(HttpPostedFileBase CallersMessage)
{
if (CallersMessage != null && CallersMessage.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(CallersMessage.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath(recordingPath), fileName);
_log.Debug("Received recording and will save as " + path);
CallersMessage.SaveAs(path);
}
string vm_id = Request.QueryString["vm_id"];
string vm_event = Request.QueryString["vm_event"];
string vm_result = "";
return VoiceView(vm_id, vm_event, vm_result);
}

Related

Android webview - how to pass a large binray file to Javascript

I have a mobile app that wraps around the web-app, using webview.
The web-app has a button to open a large .zip file (e.g. 100 MB).
The user clicks a button, and selects a .zip file.
This triggers an onChange function with a variable of type File (Blob), which includes attributes like:
file name
file size
file type (application/zip)
The javascript code then parses the .zip file, extracts specific data within it and uses it within the web-app.
This works well within the web-app, when the app is called via the Chrome browser.
For example when operated in chrome browser on an Android phone, I can pull the .zip file and open it in the web-app.
I want to do the same but using the mobile app.
I am able to pick up the .zip file using a File Chooser, but I have problems to fetch the file from the Javascript code.
When calling fetch(fileUri) from the Javascript side I'm getting errors.
I'm using the following uri
/storage/emulated/0/Android/data/com.example/files/Download/file2.zip
The fetch succeeds but returns a blob with size of 165 (i.e. not the actual size of the file) which hosts the error message:
{
"error": "Not Found",
"message": "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again."
}
The program flow is like so:
I select a .zip file via FileChooser.
In onActivityResult, the uri value is /document/msf:12858 (seen via uri = intent.getData();)
The uri needs to be mapped into a real path file url, such that the fileUrl will be passed to Javascript (via webview).
Javascript will then fetch the file using the fileUrl.
I searched how to get the real path file url when selecting a file with FileChooser, and found
this, and this links.
I wasn't able to get the real file path, so I decided to read the file and write it to another location, so I can get a file path. (this is not efficient and done just to check the functionality).
I create the new file using the following code:
InputStream stream = context.getContentResolver().openInputStream(uri);
File file2 = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "file2.zip");
writeBytesToFile(stream, file2);
I don't see any errors when creating the file, and when creating the file, the number of bytes that are read and written to the new file are as expected.
For file2, I get a value of:
/storage/emulated/0/Android/data/com.example/files/Download/file2.zip
Then, within the Javascript code I fetch this file path.
But I'm getting a Blob with the "file-not-found" content as above.
So:
How can I verify that the file is indeed created and that the path can be fetched from Javascript?
How can I get the real file path of the original selected file, so I don't have to read and write the original file to new location just to get the file path?
Thanks
EDIT1:
I have "Intent intent" and not "Intent data" in the signature of onActivityResult.
I replaced String filePath = intent.getData() with
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
try {
intent_to_resolve = new JSONObject();
if (resultCode == RESULT_OK) {
// try1
String filePath1 = intent.getData().toString();
Log.d("Verbose", "filePath1: " + filePath1);
// try2
String filePath2 = intent.toString();
Log.d("Verbose", "filePath2: " + filePath2);
...
I'm getting the following value for filePath:
filePath1: content://com.android.providers.downloads.documents/document/msf%3A12858
filePath2: Intent { dat=content://com.android.providers.downloads.documents/document/msf:12858 flg=0x43 }

QuickBlox file attachments received without extension

I am developing a NativeScript Android app and using QuickBlox.
I can open images and audio files inside the app, but there are some issues with .pdf, Word and Excel documents.
Code written by a co-worker:
var attID = message.attachments[0].id
var fileSrc = ChatManager.getQB().content.publicUrl(attID) + "/" + "/download.xml?token=" + ChatManager.getSessionToken()
I get the URL with blob + session token, then:
var intent = new android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(args.object.src));
intent.addCategory(android.content.Intent.CATEGORY_BROWSABLE);
application.android.startActivity.startActivity(intent);
In this way I successfully download .pdf files, but .doc, .docx, .xls and .xlsx return without extension.
I also tried getting the URL through privateUrl() (without interpolating the token), with the same result.
Another not working method:
httpModule.request({
url: uid,
method: 'GET',
headers: {
'QuickBlox-REST-API-Version': '0.1.0',
'QB-Token': ChatManager.getSessionToken()
}
}).then(res => {
var file = res.content.toFile();
var intent = new android.content.Intent(android.content.Intent.ACTION_VIEW);
var uri = android.net.Uri.fromFile(new java.io.File(file.path));
intent.setDataAndType(uri, 'application/pdf');
application.android.startActivity.startActivity(android.content.Intent.createChooser(intent, 'Apri file...'));
});
Any way I try, it feels like QuickBlox returns the extension on .pdf files only. Any suggestions?
UPDATE:
I tried opening the URL on different devices.
https://api.quickblox.com/blobs/[blobId]?token=[token]
On Chrome for Windows and iOS Safari, the file is downloaded or opened in browser correctly. On Android, it returns without extension on these browsers: Chrome e LineageOS stock browser. On Internet Samsung 7.4.00.70, it's opened in the browser correctly.
With httpModule.request(), I get this warning in the debug console on result:
Resource interpreted as Document but transferred with MIME type [my file mime type]
At the moment I am using this workaround in native code, but later I'll need to find something that works on iOS too.
I'm not marking this as an answer since it doesn't solve the problem
var r = new android.app.DownloadManager.Request(android.net.Uri.parse(args.object.src));
r.setDestinationInExternalPublicDir(android.os.Environment.DIRECTORY_DOWNLOADS, fileName.text);
r.allowScanningByMediaScanner();
r.setNotificationVisibility(android.app.DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
var dm = application.android.startActivity.getSystemService(android.content.Context.DOWNLOAD_SERVICE);
dm.enqueue(r);

How to get object from Google cloud storage bucket

I have used this below code for get object from google cloud storage bucket.i have error in getMetadata. Can any one please tell me here what is getMetadata and how to get that ?
Storage.Objects.Get getObject = client.objects().get(bucketName, objectname);
if (getMetadata == true) {
StorageObject object = getObject.execute();
} else {
// Downloading data.
ByteArrayOutputStream out = new ByteArrayOutputStream();
// If you're not in AppEngine, download the whole thing in one request, if possible.
getObject.getMediaHttpDownloader().setDirectDownloadEnabled(true);
getObject.executeMediaAndDownloadTo(out);
}
It looks like you're running through the sample code snippet; in that snippet, getMetadata is simply referring to your own choice of whether you want to view the object's metadata like size, content-type, creation time, etc., or whether you actually want to download the object's contents.
In your actual code using it, you probably won't structure it that way using any getMetadata variable. Instead, you should just use the code from the branch of that conditional that you need in each particular circumstance. For example, if you just want to get the size of the object so that you can display the number of bytes somewhere without actually downloading it:
Storage.Objects.Get getObject = client.objects().get(bucketName, objectname);
StorageObject object = getObject.execute();
System.out.println("Size is: " + object.getSize().longValue());
Or if you just wanted to dump the contents to System.out:
Storage.Objects.Get getObject = client.objects().get(bucketName, objectname);
getObject.getMediaHttpDownloader().setDirectDownloadEnabled(true);
getObject.executeMediaAndDownloadTo(System.out);

How to create a blob in Android HTML5 app

My server spits out the source of a PDF. With XHR2 I request that code using xhr.responseType = 'blob'; For iOS I then just use
blob = new Blob([this.response], {type: "application/pdf"});
and then save it using Phonegap's Filewriter. When I then open the saved file, I have a perfect PDF. I simply can't get anything similar to work on Android. My last attempt was:
if (!window.BlobBuilder && window.WebKitBlobBuilder){
window.BlobBuilder = window.WebKitBlobBuilder;
var bb = new window.BlobBuilder();
bb.append(this.response);
blob = bb.getBlob("application/pdf");}
since Android coughed over just plain 'BlobBuilder'. That duly creates a PDF which FileWriter then saves. The files structure is presumably OK as a PDF since PDF readers open it without complaint. Unfortunately, the PDF is completely blank.
I just don't seem to be able to get my elderly head around whatever is required by Android.

Returning an XML file from a web service to android device?

I have a set of mp3 files on my computer which i want to be the server.
Now i have a web service(Songs_Collection). This web service returns the list of all songs present on the server to the user.The user can download the desired file directly from the server.
I have a small problem :
How does my web service get the list of audio files kept on the server in the folder c:\Audio Files.
Someone suggested that i need to keep the names in a "Web Content" folder, but can anyone suggest how should i approach it?
I worked out on this part . But now how do I send it to the client on device ?
Can i send it directly as an array? (I guess then some seriliazation-deserialization needs to be done. please suggest)
Or If send it as an XML file then how should I proceed? (This is more important)
This is working perfectly fine :
for-
public static void main(String[] args) {
File directory=new File("C:/copyimages");
String filename[] = directory.list();
for (int i = 0; i < filename.length; i++) {
System.out.println("\n");
String listFilenames = filename[i];
System.out.print(listFilenames);
}
}

Categories

Resources