ASP .net 6 download file by httpclient - problem with stream - asp.net

I'm creating blazor server app. I use external file storage with RestAPI.
I want to create download button to get file from storage. This may seem easy, but not necessarily.
From file storage I download HttpContent like that
var request = new HttpRequestMessage(HttpMethod.Get, _url);
request.Headers.Add("auth-token", token);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));
HttpResponseMessage response = await _Http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
response.EnsureSuccessStatusCode();
var content = response.Content;
next I act like this tutorial https://learn.microsoft.com/en-us/aspnet/core/blazor/file-downloads?view=aspnetcore-6.0
var fileStream = content.ReadAsStream();
using (var streamRef = new DotNetStreamReference(fileStream))
{
await JS.InvokeVoidAsync("downloadFileFromStream", "file.txt", streamRef);
}
For small files everything work great. But if I try to download large file (100mb), algoritm firstable download file to memory(RAM) of server and later save on local disk of client.
In ideal world I dream that when I click button download, file from external storage will download after delay (with progressbar) like physical file (no stream buffer) form http server e.g. https://www.example.com/file.txt. Of course by my BlazorServer Application with authorization and authentication, and whole neccesery services.

I have solution.
Create Service to service File Storage API
Create controller to avoid cros-origin error
Use microsoft tutorial to create download button https://learn.microsoft.com/en-us/aspnet/core/blazor/file-downloads?view=aspnetcore-6.0

Related

Uploading images to a server with blob

I have both asp.net API and vue.js Front. I want to upload images to my blob azure storage. Is it better to do it on API side? I mean send image to API and from API to blob Azure or directly from vue.js to blob azure?
Ideally we should try to send the image as POST to the API in ASP.NET and then call the API for uploading the image.
Instead of taking the image directly and uploading, we must check if the file is not corrupted (or any other issue) and then upload it.
In .NET, try out the below code:
string loc = Directory.GetCurrentDirectory() + "/" + location;
CloudStorageAccount account = CloudStorageAccount.Parse(*connection_string*);
CloudBlobClient client = account.CreateCloudBlobClient();
CloudBlobContainer container = client.GetContainerReference(*container_name*);
container.CreateIfNotExists();
CloudBlockBlob blob = container.GetBlockBlobReference(*blobName*);
blob.UploadFromFile(loc);

How to get uri to included asset in Uno Platform?

For integrating with a android binding project I need to provide a Uri pointing to a .zip file, which I have included in the assets and designated as AndroidAsset. How do I get the Uri for such a file?
I already tried ms-appx:///Assets/file.zip and file:///Assets/file.zip
Update:
Import to note is, that the function consuming the Uri is Android native code, so I suspect that ms-appx:// doesn't get resolved properly.
Update2:
It is not possible to provide a stream.
The method I am calling is shown in the sample here: https://github.com/Laerdal/Xamarin.Nordic.DFU.Android/blob/7244627c09e97e05ee2c8e05744f19055981486b/Sample/Nordic/FirmwareUpdater.cs#L27.
_dfuServiceInitiator.SetZip(firmwareZipFile);
The native implementation is shown here: https://github.com/NordicSemiconductor/Android-DFU-Library/blob/07bdaa50cfc5786790bf1ac589b14931de65d099/dfu/src/main/java/no/nordicsemi/android/dfu/DfuServiceInitiator.java#L620
public DfuServiceInitiator setZip(#NonNull final Uri uri) {
return init(uri, null, 0, DfuBaseService.TYPE_AUTO, DfuBaseService.MIME_TYPE_ZIP);
}
Files read from the StorageFile.GetFileFromApplicationUriAsync() method may not return a stable path on UWP, and this is particularly the case on particularly on Android or WebAssembly, where the file is not necessarily on the file system.
On Android, the file is a Stream directly built from the APK file, and on WebAssembly it is stored in a temporary location.
In order to use keep a stable copy of the file, use the following:
var file = await StorageFile.GetFileFromApplicationUriAsync(new System.Uri("ms-appx:///TextFile.txt"));
var newFile = await file.CopyAsync(Windows.Storage.ApplicationData.Current.LocalFolder, file.Name, NameCollisionOption.ReplaceExisting);
var txt = await FileIO.ReadTextAsync(newFile);
The method StorageFile.GetFileFromApplicationUriAsync can be used to get a StorageFile object from an ms-appx Uri.
Then you can use the Path property of the StoragFile to get the local android path. Make note to set the build action of the file as Content.
var file = await StorageFile.GetFileFromApplicationUriAsync(new System.Uri("ms-appx:///Assets/file.zip"));
Android.Net.Uri zipUri = Android.Net.Uri.Parse("file:///"+file.Path);

Get XML request file processed during service call

We have third party service and writing below code to execute. After adding its service reference it gives us object.
client objClient = new client();
info objEntities = new info();
objEntities.reginfo = new reginfoRequest();
response objResp = objClient.registerInfo(objEntities);
I have enabled Diagnostic and it records XML in .svclog file.
** But what I want to do is.. I want to record each XML file during processing and record each XML file in specific folder.
How can I do that?
What about using Fiddler ?
There you can see all requests and responses.

copy file from local to remote server

I'm dynamically creating html files on my local system (using HTMLTEXTWRITER, then save them using streamwriter to local file system). I want to copy this file to my remote server withour user interaction, so that my users can read file. I use C#
for instance I want to copy from d:\myfile.html to mysite.com\myfile.html, how can I do it?
I have used this and it worked. may be useful
for holding path of local
rPath = "\\" & Request.UserHostAddress & "\c$\temp\"
for output file
rOutput = Session.SessionID & "_" & Format(Date.Now(), "ddMMyyhhmmss") & ".pdf"
now: report will be created at localhost\c\temp
You can't use the System.IO classes for this (unless you have access to the remote server as a network drive), but you can programmatically POST the file from the client to the remote server over HTTP using System.Net.
Here's a snippet using the WebRequest class:
WebRequest request = WebRequest.Create( url );
request.Timeout = 1000; // some appropriate value
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = 0; // set a length here
using( StreamWriter requestStream = new StreamWriter( request.GetRequestStream(), System.Text.Encoding.UTF8) ) {
// write to the stream here using requestStream.Write();
requestStream.Close();
}
More info for HTTP: http://msdn.microsoft.com/en-us/library/debx8sh9.aspx
Alternatively, you could use a protocol designed for transferring files like FTP (or something more secure) which isn't that hard to do in code.
FTP options: http://msdn.microsoft.com/en-us/library/ms229718
Is you remote server based on Windows and in the same workgroup or domain with you working machine ? If so, you can turn on the Windows File Sharing on the server. Then you can copy your file with cmd like this:
copy c:\test.txt \\mysite.com
The path "\\mysite.com" is also valid used by File.Copy in C#.
Otherwise, you need to set up a FTP environment on you server and use the FTP related API in C#.
You could set-up an FTP server and copy the files programmatically via FTP.
An example would be found here or here.
There are three ways by which you can copy the file to remote server.
Using normal file copy mode. Here you need to have access to the the webserver shared path. If the webserver is in same network as your application, then you can share the webroot and provide write access to the user who is running the application. He can then use File.Copy("source.txt", "\\Servername\SharedFolderName\target.txt").
The second approach is to use FTP to copy the file to the remote server. This MSDN example would help you on how to do this. This will work with most of the shared hosting providers.
You can use HTTP POST as noted by Tim. But this would let any user to perform the post. You may have to take care of user provisioning, authentication and authorization. IMO, keep this as last option as provisioning user and providing rights to certain path, may become cumbersome.

iis7 website accessed externally downloads files to server instead of local machine

I've a site set up in IIS. It's allows users to download files from a remote cloud to their own local desktop. HOWEVER, the context seems to be mixed up, because when I access the website externally via the IP, and execute the download, it saves the file to the server hosting the site, and not locally. What's going on??
My relevant lines code:
using (var sw2 = new FileStream(filePath,FileMode.Create))
{
try
{
var request = new RestRequest("drives/{chunk}");
RestResponse resp2 = client.Execute(request);
sw2.Write(resp2.RawBytes, 0, resp2.RawBytes.Length);
}
}
Your code is writing a file to the local filesystem of the server. If you want to send the file to the client, you need to do something like
Response.BinaryWrite(resp2.RawBytes);
The Response object is what you use to send data back to the client who made the request to your page.
I imagine that code snippet you posted is running in some sort of code-behind somewhere. That is running on the server - it's not going to be running on the client. You will need to write those bytes in the Response object and specify what content-type, etc. and allow the user to Save the file himself.

Resources