How to download zip file from url in unity? - android

I am using unity 2019.2.14f1 and visual studio 2019.I also tried with ICSharpCode.SharpZipLib but can't find any solution.I am trying with the code from the code which is available in the following url:
Unzip a memorystream (Contains the zip file) and get the files
Thanks in advance.

You can download files in Unity using UnityWebRequest.Get. Note that using it like in the example shown on that page, you're going to want to make sure you know how to use Unity's Coroutines.
Also, instead of downloadHandler.text you're going to want to use downloadHandler.data to get the downloaded data as bytes you can put into a stream.
Once you've got those you can use the appropriate libraries or standard library calls to unzip your files.

To download a file from a URL you can use system.net
WebClient client = new WebClient();
client.DownloadFile("http://whateverlinkyouhave.zip", #"C:\whateverlinkyouhave.zip")

Everyone's answer is correct, especially using UnityWebRequest. One of things you must do is to turn the byte[] data to zip file. And then use some Unzip library.
Example implementation
using System;
using UnityEngine.Networking;
private IEnumerator DownloadZipFile(string url)
{
using (UnityWebRequest www = UnityWebRequest.Get(url))
{
yield return www.Send();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
string savePath = string savePath = string.Format("{0}/{1}.zip", Application.persistentDataPath, "zip_file_name");
System.IO.File.WriteAllBytes(savePath, www.downloadHandler.data);
}
}
}
Hope it helps.

Related

Reading and existing file in Xamarin withC#

This code works:
string file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "File.text");
File.ReadAllText(file);
Pretty straight-forward, but when I display the variable "file" using a Pizel 5 simulator I get a weird path: /data/user/0/com.companyname.aikidohours/files/.local/share/File.text. I can write new data to the file and read from it. but I now want to read from an existing file and I can't figure out where to put the file. Can someone tell where to put a text file full of basic information that I need to read from in Xamarin for adnroid?
Thanks
Todd
If you want to deploy that file with your application, you can add it to the 'Assets' folder inside your_project_name.Android project.
WARNING!!! File put in this folder are READONLY!
In case this is ok for you,this is the code to access the file:
using Xamarin.Essentials;
using (var reader = new StreamReader(await FileSystem.OpenAppPackageFileAsync("file_path")))
{
string content = reader.ReadToEnd();
}

How to access Steaming Assets folder?

So in my project I have an image object that loads various different sprites throughout the game. In order to implement this, I have a folder with a bunch of .pngs that the game accesses. In order for this to work in a standalone build I put these images in the following path:
StreamingAssets/Question Images
However, in Android I am getting an error because, as the manual says:
"On Android, the files are contained within a compressed .jar file (which is essentially the same format as standard zip-compressed files). This means that if you do not use Unity’s WWW class to retrieve the file, you need to use additional software to see inside the .jar archive and obtain the file.
The thing is I have no idea how to go about implementing this, any ideas?
From Application.streamingAssetsPath
It is not possible to access the StreamingAssets folder on WebGL and Android platforms. No file access is available on WebGL. Android uses a compressed .apk file. These platforms return a URL. Use the UnityWebRequest class to access the Assets.
Example using UnityWebRequestTexture
private void Start()
{
StartCoroutine(GetTexture());
}
private IEnumerator GetTexture()
{
// in general I would always avoid to have spaces in file-paths
var path = Path.Combine(Application.streamingAssetsPath, "QuestionImages", "exampleImage.png");
using(var www = UnityWebRequestTexture.GetTexture(path))
{
yield return www.SendWebRequest();
if(www.isNetworkError || www.isHttpError)
{
Debug.LogErrorFormat(this, "Unable to load texture due to {0} - {1}", www.responseCode, www.error);
}
else
{
Texture myTexture = ((DownloadHandlerTexture)www.downloadHandler).texture;
}
}
}
Note: Typed on smartphone so no warrenty but I hope the idea gets clear.

How to download file with new Dropbox API?

Dropbox now have an apsolutely new API, which is absolutely differ from the old one (it's interesting why), but there's no ANY actual examples in the internet, so I've found only some code in their examples. Here is it:
// Download the file.
try (OutputStream outputStream = new FileOutputStream (file)) {
mDbxClient.files ()
.download (metadata.getPathLower (), metadata.getRev ())
.download (outputStream);
}
I need to download file from remote folder to the local one, so I need to use this path for example:
.download ("Backups/backup.ab", "/storage/sdcard/Folder/backup.ab")
I've tried it, but get a error
IllegalArgumentException: String 'rev' does not match pattern'
Do you know, what it can be, and metadata.getPathLower () and metadata.getRev () methods are using for? I've learned, that metadata var gets from the first argv from execute (), but what this functions do?
Thanks a lot!
Not sure if if works for android. I have posted the following method just in case someone is looking for a C# .net solution.
private async Task Download(DropboxClient dbx, string folder, string file, string localFilePath)
{
using (var response = await dbx.Files.DownloadAsync(folder + "/" + file))
{
using (var fileStream = File.Create(localFilePath))
{
(await response.GetContentAsStreamAsync()).CopyTo(fileStream);
}
}
}
Parameter example:
file = "YourFileName.pdf";
folder = "/YourDropboxFolderName";
localFilePath = #"C:\Users\YourUserName\YourFileName.pdf";
The Dropbox API v2 Java SDK's download method takes these two parameters:
String path
String rev
Per the download method documentation there, the first is the remote path of the file in Dropbox you want to download, and the second is the identifier for the revision of the file you want. The second parameter is not the local path where you want to save the file, as it appears you're supplying in your code. Instead, you save the file content using the .download (outputStream); portion of the sample code you posted, e.g., as also shown in this sample code.
Also, as stated in the documentation, the second parameter is deprecated and should no longer be used. You can just use the version of the download method that only takes the one parameter. The code for using it is otherwise the same as the sample.
For reference, in the sample, the metadata object is an instance of FileMetadata. You can find more information on the getPathLower and getRev methods in the documentation as well.

Cordova App - Open PDF from Expansion File and convert to Base64 String

I have a cordova app up and running where I have an expansion file that is hosting a lot of pdf documents. I want to be able to open a pdf file from that expansion file and convert the entire file into a base 64 string in order to print that pdf from my app. I am trying to use this cordova plugin: https://github.com/sarahgoldman/cordova-print-pdf-plugin which is great, but there is no explanation on how to actually create the base 64 string.
I have attempted to use
var files = new File([""], "filename.pdf",{type:'application/pdf'});
console.log(files);
if (files.length > 0) {
getBase64(files[0]);
}
});
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
where the filename.pdf is stored in my expansion file but I don't get a proper response from the code.
any help would be greatly appreciated.
Thank you,
You're really asking two questions in one.
Expansion Files in Cordova
To get at the content of your expansion file, I suggest this cordova plugin:
https://github.com/agamemnus/cordova-plugin-xapkreader/tree/cordova-6.5.0
it facilitates accessing files inside of the expansion file so you can do something like this:
<img src="content://com.test.expansion/myfile.png">
Key is to follow the installation instructions to the point because this plugin requires more work than most of the other ones I've installed.
Base64 Encoding in Javascript
look at the btoa() and atob() functions. They convert text to and from base64 encoding.
Feed your PDF content to the function and hand that over to the pdf plugin.

How to correctly load XML files on mobile devices using unity3d

I have some level definitions in xml format (with .txt extension) inside (without any subfolders) my project's rescources folder
I for more scalability, I have a plain text file naming all these level definition XMLs
I read that file using
TextAsset WorldList = (TextAsset)Resources.Load("WorldList");
And then I load the needed world:
TextAsset TA = (TextAsset)Resources.Load(/*"LevelDefs/" +*/ Worlds[worldToload]);
xps.parseXml(TA.text);
loadLevel(levelToLoad);
(you see that I have moved these rescources out of subfolder to reduce the chance of them not loading)
worldToload here is the index number of that world
program works fine on windows but nothing loads on my android test device.
I seem to have problems debugging on device so I only guess something went wrong in loading phase.
any suggestions?
From Unity Documentation:
Most assets in Unity are combined into the project when it is built.
However, it is sometimes useful to place files into the normal
filesystem on the target machine to make them accessible via a
pathname. An example of this is the deployment of a movie file on iOS
devices; the original movie file must be available from a location in
the filesystem to be played by the PlayMovie function.
Any files placed in a folder called StreamingAssets in a Unity project
will be copied verbatim to a particular folder on the target machine.
You can retrieve the folder using the Application.streamingAssetsPath
property. It’s always best to use Application.streamingAssetsPath to
get the location of the StreamingAssets folder, it will always point
to the correct location on the platform where the application is
running.
So below snippet should work:
// Put your file to "YOUR_UNITY_PROJ/Assets/StreamingAssets"
// example: "YOUR_UNITY_PROJ/Assets/StreamingAssets/Your.xml"
if (Application.platform == RuntimePlatform.Android)
{
// Android
string oriPath = System.IO.Path.Combine(Application.streamingAssetsPath, "Your.xml");
// Android only use WWW to read file
WWW reader = new WWW(oriPath);
while ( ! reader.isDone) {}
realPath = Application.persistentDataPath + "/Your"; // no extension ".xml"
var contents = System.IO.File.ReadAll(realPath);
}
else // e.g. iOS
{
dbPath = System.IO.Path.Combine(Application.streamingAssetsPath, "Your.xml");
}
Thanks to David I have resolved this problem.
for more precision I add some small details:
1-As David points out in his answer (and as stated in unity documentations), we should use StreamingAssets if we want to have the same folder structure. One should use Application.streamingAssetsPathto retrieve the path.
However, files are still in the apk package in android's case, so they should be accessed using unity android's www class.
a good practice here is to create a method to read the file (even mandatory if you are going to read more than one file)
here is one such method:
private IEnumerator LoadDataFromResources(string v)
{
WWW fileInfo = new WWW(v);
yield return fileInfo;
if (string.IsNullOrEmpty(fileInfo.error))
{
fileContents = fileInfo.text;
}
else
fileContents = fileInfo.error;
}
This is a coroutine, and to use it we need to call it using
yield return StartCoroutine(LoadDataFromResources(path + "/fileName.ext"));
Yet another remark: we can not write into this file or modify it as it's still inside the apk package.

Categories

Resources