not able to download file with size more than 63kb using UnityWebRequest - unity3d

i am try to download asset bundle from an url but the request keep on cancelling after downloading 63kb. Can anyone explain to me why this may be happening?
My Code :
public IEnumerator DL()
{
string downloadlink = "https://drive.google.com/file/d/1OGyrB4-MQfo-HVom9ENvV4dn312_wL4Q/view?usp=sharing";
string filepath = Application.persistentDataPath + "/electroplatingNN";
//Download
UnityWebRequest dlreq = new UnityWebRequest(downloadlink);
dlreq.downloadHandler = new DownloadHandlerFile(filepath);
dlreq.timeout = 15;
UnityWebRequestAsyncOperation op = dlreq.SendWebRequest();
while (!op.isDone)
{
//here you can see download progress
Debug.Log(dlreq.downloadedBytes / 1000 + "KB");
yield return null;
}
if (dlreq.isNetworkError || dlreq.isHttpError)
{
Debug.Log(dlreq.error);
}
else
{
Debug.Log("download success");
}
dlreq.Dispose();
yield return null;
}

As already mentioned in the comments the issue is not in the UnityWebrequest but rather Google Drive doesn't simply download your file as you expect.
Instead the data you download is actually only the web page which would allow you to download it. If I simply open your file in a browser I get a page looking like this
where I now could download your file.
There are packages like this or this which implement the necessary stuff for actually download files from Google Drive API in Unity.

Related

How to save/share a file in Net. Maui without savefiledialog?

My MauiBlazorApp can create a .pdf file. In what ways can I make this file accessible for the users of windows/android/IOS. A SaveFile Dialog is not yet implemented in Maui. With this path
string SaveToPath = System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, "hello.pdf");
I can save it on a windows machine and open it (tested).
The path (FileSystem.Current.AppDataDirectory) on a local android device (phone connected to windows maschine via usb) is something like this:
/data/user/0/com.companyname.appname/files/hello.pdf
But later I can't find this folder on my phone. I find this:
/data/com.companyname.appname/cache/ empty folders all the way
Why can't I save a file in .../downloads
How do you import/export data from 'device to device' in Maui? Files seems to be not the way. Email with attechments? Is that possible/better?
You can check the Maui File picker, It provides the method you can pick the file from the device.
public async Task<FileResult> PickAndShow(PickOptions options)
{
try
{
var result = await FilePicker.Default.PickAsync(options);
if (result != null)
{
if (result.FileName.EndsWith("jpg", StringComparison.OrdinalIgnoreCase) ||
result.FileName.EndsWith("png", StringComparison.OrdinalIgnoreCase))
{
using var stream = await result.OpenReadAsync();
var image = ImageSource.FromStream(() => stream);
}
}
return result;
}
catch (Exception ex)
{
// The user canceled or something went wrong
}
return null;
}
In addition, you can refer to Folder Picker .NET MAUI. This is more detailed.

How to use WriteAllBytes if using UnityWebRequest?

I use UnityWebRequest in getting the file on streamingassets folder because WWW is obsolete, now on FileWriteAllBytes i cant right downloader.bytes because it is return an error to me can someone help me
#if UNITY_ANDROID
// path on streamingasset folder
string path = System.IO.Path.Combine(Application.streamingAssetsPath, "game.dat");
UnityWebRequest downloader = UnityWebRequest.Get(path);
yield return downloader.SendWebRequest();
while (!downloader.isDone)
{
// nothing to be done while downloader gets our db file
}
// then save to application.persistentdatapath
// on this second param i dont know what do right i cant put donwloader.bytes because is obsolete
File.WriteAllBytes(dataFilePath, missing);
#endif
use DownloadHandler
UnityWebRequest downloader = UnityWebRequest.Get(path);
yield return downloader.SendWebRequest();
DownloadHandler handler = downloader.downloadHandler;
File.WriteAllBytes(dataFilePath, handler.data);

Failed to decompress data for the AssetBundle 'Memory'. -- Unity3D AssetBundle Loading

IEnumerator WWWLoader()
{
WWW bundleRequest = new WWW("*****************");
while(!bundleRequest.isDone)
{
yield return null;
}
AssetBundle bundle = null;
if (bundleRequest.bytesDownloaded > 0)
{
AssetBundleCreateRequest myRequest = AssetBundle.LoadFromMemoryAsync(bundleRequest.bytes);
while(!myRequest.isDone)
{
Debug.Log("loading....");
yield return null;
}
if (myRequest.assetBundle != null)
{
bundle = myRequest.assetBundle;
GameObject model = null;
if (bundle != null)
{
AssetBundleRequest newRequest = bundle.LoadAssetAsync<GameObject>("Log");
while (!newRequest.isDone)
{
Debug.Log("loading ASSET....");
yield return null;
}
model = (GameObject)newRequest.asset;
bundle.Unload(false);
}
}
else
{
Debug.LogError("COULDN'T DOWNLOAD ASSET BUNDLE FROM URL (assetBundle = null)");
}
}
else
{
Debug.LogError("COULDN'T DOWNLOAD ASSET BUNDLE FROM URL (0 bytes)");
}
}
This is my code to load an AssetBundle (I've removed the URL). It gives me the error "Failed to decompress data for the AssetBundle 'Memory'." I'm not sure if 'Memory' is referring to the AssetBundle name because mine is called 'log' so is it referring to a problem with memory? Any help on understanding this error and fixing it is much appreciated.
I believe your issue related to the compression being used when the bundles are built. You may need to use LoadFromMemoryAsync instead. https://docs.unity3d.com/ScriptReference/AssetBundle.LoadFromMemoryAsync.html
So, I have gotten past the error by using UnityWebRequestAssetBundle as shown here (recommended by derHugo).
I was initially using a simple FTP server to access the assets and it would not allow me to download them (from Unity, but in a browser it worked fine). I then switched to using a Flask server, which worked like a charm.
Note to people finding this like I did; if you're using Asset Bundles for webgl, you need to make sure the assetbundles are uncompressed (BuildAssetBundleOptions.UncompressedAssetBundle). Docs mention it but it can be easy to miss, and the default is LZMA.

How to upload image file in Xamarin forms using rest api . Have issues with large images

I tried and I face a problem when uploading images greater than 570 kb. This issue is in Xamarin Forms for android and PHP rest api. I tested the rest api separately and I have no issues there uploading 2mb files using postman.
Tried various ways also by giving some delay. I am capturing image using cross.media plugin. Then navigating to another page to upload. I wait for sometime and then click the button to upload. I am not able ascertain where the issue is.
System.IO.Stream fileStream = System.IO.File.Open(file, FileMode.Open);
byte[] data = ReadFully(fileStream);
fileStream.Close();
MultipartFormDataContent multi = new MultipartFormDataContent();
ByteArrayContent imageStream = new ByteArrayContent(data);
StringContent SequenceID = new StringContent(osequence);
imageStream.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
imageStream.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = osequence, // "screenshot.jpg", // generate this and send
Name = "avatar",
};
multi.Add(imageStream);
alertLabel.Text = "Uploading Now";
var response = await App.client.PostAsync(url, multi);
string responsestr = response.Content.ReadAsStringAsync().Result;
var retresponse = new retResponse();
bool uploadSuccess = false;
I have made the rest api to send response on error and showing the same in an alert box as below
if (responsestr != "") alertLabel.Text = responsestr.ToString();
else alertLabel.Text = alertLabel.Text + " After Upload Command ";
}
catch (Exception e)
{
}
} // private void upload(MediaFile mediaFile)
The error I get is no file sent
Please ignore the above question. The problem was solved by changing the PHP.ini max upload file size. The file size in the device was around 500 - 700 KB . don't know how it comes to 1.99 and 2 mb when uploaded. Increasing max file size solved it.

error accessing a file for Facebook upload

i am trying to upload a video to the users Facebook wall i have the FacebookMobile.uploadVideo in place and appears to to be fine but am getting the following error from facebook:
(#353) You must select a video file to upload.
i think the problem is in accessing the video file for some reason.
public function handleUpload(ev:TouchEvent)
{
trace ("posting to facebook"+ accessCamera.filePath);
var videoInfo:Object = new Object;
videoInfo.title = "test upload on FB api",
videoInfo.description = accessCamera.filePath,
videoInfo.fileName = accessCamera.filePath;
videoInfo.video = accessCamera.filePath;
FacebookMobile.uploadVideo('me/videos', onComplete, videoInfo);
}
private function onComplete( result:Object, fail:Object ):void
{
trace("facebook post onComplete called" );
if (result)
{
//result.id is id of post that was just posted
trace ("great");
}
else if (fail)
{
trace("post Failed");
trace('code: '+fail.error.code);
trace('message: '+fail.error.message);
trace('type: '+fail.error.type);
}
}
accessCamera.filepath is the var where the video file is located on the device and looks like this when traced : file:///mnt/sdcard2/DCIM/Camera/VID_20140304_105813.mp4
Am I accessing the file correctly, does it need to be loaded by the app or is a path fine.
any help would be greatly appreciated.
the issue is i was passing a string variable containing the file location into the params object and the FacebookMobile.uploadVideo requires either a fileReferance or byteArray.