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

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.

Related

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

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.

How to upload an image from a tablet running Windows 8.1 metro application?

I need to upload an image to a server, less then 20 lines of code please. and no questions about services. My boss expects it to work like ftp of old days...
I don't think there is a 20 lines solution to your problem.
But check this link out :
http://code.msdn.microsoft.com/Windows-8-SocketsFtp-4fc23b33#content
It contains a full Ftp client that works on Windows 8.1 metro application.
You could use this project as a library in your own project.
If you especially need to upload file, I think you need to use the UploadFileAsync function in FtpClient class
public async Task UploadFileAsync(StorageFile file, string destination)
{
using (var stream = await OpenWriteAsync(destination))
{
//
// A more efficient way, maybe a DataReader can be used here
using (var readStream = await file.OpenReadAsync())
{
var buffer = new byte[512].AsBuffer();
var resultingBuffer = new byte[0];
while (true)
{
IBuffer readBuffer = await readStream.ReadAsync(buffer, 512, InputStreamOptions.Partial);
if (readBuffer.Length == 0) break;
resultingBuffer = resultingBuffer.Concat(readBuffer.ToArray()).ToArray();
}
await stream.WriteAsync(resultingBuffer.AsBuffer());
await stream.FlushAsync();
}
}
}

samsung smart tv upload file

On the samsung dforum I found the URL which explains a function startUpload().
but also in forums i found people saying that uploading files by any means is not possible. If so why samsung provide the startUpload() function?
Did anybody tried file upload? please help
Documentation is incorrect. I tested it on UE46ES8000 and successfully uploaded file from USB flash drive connected to TV.
OnComplete callback called instead of OnUploadComplete.
To the end of uploaded data appended string --END_OF_PART--. If you strip it from file, you get your original file.
function OnUploadComplete (msg) {
alert('***OnUploadComplete***' + msg );
}
function OnUploadProgress (msg) {
alert('***OnUploadProgress***' + msg );
}
function fnDnStatus (msg) {
alert('fnCallback' + msg );
var tArrResult = msg.split("?");
for (var i=0; i < tArrResult.length; i++) {
alert("tArrResult[" + i + "] = " + tArrResult[i]);
}
// DownResult: If res=1 success, otherwise ERROR (see end of this file)
}
var DownloadPlugin = document.getElementById("pluginObjectDownload");
DownloadPlugin.OnUploadComplete = OnUploadComplete;
DownloadPlugin.OnUploadProgress = OnUploadProgress;
DownloadPlugin.OnComplete = fnDnStatus;
var sever = '192.168.137.1',
port = 80,
header = 'Header-name: Header value',
body = '[[[FILE_BINARY]]]',
filePath = '$USB_DIR/sda1/textfile.txt',
uploadRatio = '10',
serverType = 1;
DownloadPlugin.StartUpload(sever, port, header, body, filePath, uploadRatio, serverType);
I don't know meaning of header parameter. And I don't know how to specify url other than server root. Data was sent by POST request to http://192.168.137.1:80/.
At server side I saved it with simple script (http://192.168.137.1:80/index.php):
<?php
$t = file_get_contents('php://input');
if(strlen($t) > 1){
echo 'some data arrived';
}
file_put_contents('input.txt', $t);
?>
I just uploaded a video file to my Samsung uhd, through smartthings. Hold-Click on video. Tap share. Send to device. When it's done you will see video just shared in upper right corner. Click on watch video. I'm watching it now but cant figure out where its stored on the tv

How to play secure streamed url of asset fetched dynamically through code( In Azure media services)

I am using Azure Media Services and a Silverlight Player to play the streamed url
I am able to ingest, encode the video file as an asset file but when I go play the streamed url I am facing problem.
I use following code to fetch the url...
context = new CloudMediaContext(_accountName, _accountKey);
IAsset myAsset = GetAsset("UUID:7a32b941-30bd-4c96-bf4e-26df5022eec5");
var theManifest = from f in myAsset.AssetFiles
where f.Name.EndsWith(".ism")
select f;
var manifestFile = theManifest.First();
IAccessPolicy streamingPolicy = _context.AccessPolicies.Create("Streaming policy",
TimeSpan.FromDays(10),
AccessPermissions.Read);
ILocator originLocator = _context.Locators.CreateSasLocator(myAsset, streamingPolicy, DateTime.UtcNow.AddMinutes(-500));
GetAssetSasUrlList(myAsset, originLocator);
string urlForClientStreaming = originLocator.Path + manifestFile.Name + "/manifest";
Console.WriteLine("URL to manifest for client streaming: ");
Console.WriteLine(urlForClientStreaming);
this url comes like --
https://mediasvc06w4dq5k8vd08.blob.core.windows.net/asset-064ed2d5-e42d-4c49-98eb-a712db5c614f?st=2012-12-26T23%3A04%3A22Z&se=2013-01-05T23%3A04%3A22Z&sr=c&si=9350bd2f-ec23-40b2-b27a-248bba01b97e&sig=oGgesnr8mXjCdTM5Dz%2FQpFRBDR0g0%2F60ECoXY14EvsA%3DBigBuckBunny.ism/manifest
Its not working .
When I paste this url on browser directly ,I get following error
AuthenticationFailedServer failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature. RequestId:154422cf-822e-4bbc-af2a-fa69273dfb89 Time:2012-12-27T08:57:30.9509847ZSignature fields not well formed.
But if I go and publish asset from portal( www.manage.windowsazure.com )--
I get like following url on protal..
http://mediaervices.origin.mediaservices.windows.net/5edbeae7-c3e6-45c5-bc5c-70f46b526cb5/BigBuckBunny.ism/Manifest
And it works with my silverlight player..
Now problem is that I am not getting url which starts with http from code and the url starting with https is not working with my player.
I guessed that its security issue and tried to host my player in winows azure and tried to player there but no success.
No, not a security issue. You are requesting a SAS url for a Smooth asset, you need an Origin URL. The correct code snippet is here, on my blog:
http://blog-ndrouin.azurewebsites.net/?p=1931
Specifically:
private static string GetStreamingUrl(CloudMediaContext context, string outputAssetId)
{
var daysForWhichStreamingUrlIsActive = 365;
var outputAsset = context.Assets.Where(a => a.Id == outputAssetId).FirstOrDefault();
var accessPolicy = context.AccessPolicies.Create(outputAsset.Name, TimeSpan.FromDays(daysForWhichStreamingUrlIsActive), AccessPermissions.Read | AccessPermissions.List);
var assetFiles = outputAsset.AssetFiles.ToList();
var assetFile = assetFiles.Where(f => f.Name.ToLower().EndsWith("m3u8-aapl.ism")).FirstOrDefault();
if (assetFile != null)
{
var locator = context.Locators.CreateLocator(LocatorType.OnDemandOrigin, outputAsset, accessPolicy);
Uri hlsUri = new Uri(locator.Path + assetFile.Name + "/manifest(format=m3u8-aapl)");
return hlsUri.ToString();
}
assetFile = assetFiles.Where(f => f.Name.ToLower().EndsWith(".ism")).FirstOrDefault();
if (assetFile != null)
{
var locator = context.Locators.CreateLocator(LocatorType.OnDemandOrigin, outputAsset, accessPolicy);
Uri smoothUri = new Uri(locator.Path + assetFile.Name + "/manifest");
return smoothUri.ToString();
}
assetFile = assetFiles.Where(f => f.Name.ToLower().EndsWith(".mp4")).FirstOrDefault();
if (assetFile != null)
{
var locator = context.Locators.CreateLocator(LocatorType.Sas, outputAsset, accessPolicy);
var mp4Uri = new UriBuilder(locator.Path);
mp4Uri.Path += "/" + assetFile.Name;
return mp4Uri.ToString();
}
return string.Empty;
}

error uploading files while logged in

i got a server host that only let me upload files through ftp (with code in my application).
so i got a code that works and lets me upload files to the server except with one strange thing, i can not upload files if me/user is logged in (authenticated). this is a shot in the dark to see if anybody maybe know why this is.
my error message is this
Access to the path 'D:\hshome\PATH' is denied. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.Directory.InternalCreateDirectory(String fullPath, String path, Object dirSecurityObj) at System.IO.Directory.CreateDirectory(String path) at BasicProject.Mvc.Areas.Account.Controllers.ProfileController.Test(TestViewModel viewModel)
my code i use for the upload is this
foreach (string item in Request.Files)
{
HttpPostedFileBase file = Request.Files[item];
if (file != null)
{
var path = "File";
var filePath = System.Web.HttpContext.Current.Server.MapPath("~/" + path + "/");
if (!Directory.Exists(filePath))
Directory.CreateDirectory(filePath);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://SITE/SITE/" + path + "/" + file.FileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("USER", "PASSWORD");
request.UsePassive = false;
var sourceStream = new StreamReader(file.InputStream);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();
}
like i said this works if i dont login and its a shot in the dark if you had the same issue i would be more then happy to get a piece of the solution.
When you log in, IIS is trying to impersonate you and you do not have access to that folder, only the IIS user does.
Several options to debug your code. My preference on a remote server is to add Response.write before every critical location in the file, for example after System.Web.HttpContext.Current.Server.MapPath("~/" + path + "/"); which will tell you if you got to that step and potentially (if you set it) information about the request such as the current security context/user.
Example:
foreach (string item in Request.Files)
{
HttpPostedFileBase file = Request.Files[item];
if (file != null)
{
Response.Write("A");
var path = "File";
var filePath = System.Web.HttpContext.Current.Server.MapPath("~/" + path + "/");
Response.Write("B");
if (!Directory.Exists(filePath))
{
Response.Write("C");
Directory.CreateDirectory(filePath);
}
Response.Write("D");
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://SITE/SITE/" + path + "/" + file.FileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("USER", "PASSWORD");
request.UsePassive = false;
var sourceStream = new StreamReader(file.InputStream);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();
}
If you start with that, and you see the output ABCD, then you know the problem is further down, so just repeat the process. (I find it overly distracting to add too many debugging lines at once, but you could.)
If you stop at, say "ABC", then you know that Directory.CreateDirectory(filePath); failed. You can try to do Response.Write(HttpContext.Current.User.Identity) when you are logged in and not logged in and see what you get. (I am not sure that is the property you want, but I can't test it right now, so you can try to look it up or just experiment.)
The problem was that i could not create the folder while being authenticated, so in this specific case i create folders for users when they register, and using the ftp upload code i show above its working good.