Upload to Google Drive using API C# from web user - c#

Ultimately I'm trying to upload a document from the user's file system via MVC .NET web site to Google Drive, which utilizes a service account.
I'm not sure if I'm implementing the appropriate design to accomplish the upload but I am getting hung up on the path of the file to be uploaded.
Web
#Html.TextBox("file", "file", new { type = "file", id = "fileUpload" })
Controller
public ActionResult GoogleDriveList(GoogleDrivePageVM vm, HttpPostedFileBase file)
File _file = new File();
var _uploadFile = System.IO.Path.GetFileName(file.FileName);
byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
Error occurs on the ReadAllBytes statement. It could not find file 'C:\Program Files (x86)\IIS Express\Map of Universe.txt'. The file name is correct but the path is not.
byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
... Google Drive file stuff goes here
Then upload the file from the stream.
FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, body.MimeType);
request.Upload();
So, am I going down the right path using the HTML file helper? And if so, what's the trick to get the path to work correctly? Also, I want to be able to support file sizes up to 500 MB (if that makes a difference).

If your getting the filename from a user selected windows file explorer dialog, then you shouldn't be using the below as will just strip out the filename without the path into your upload file variable and I am assuming that bogus path is where your're running the code from, so ReadAllBytes is trying to read from that path with the filename
var _uploadFile = System.IO.Path.GetFileName(file.FileName)
just change so it has that full path and filename you need to use in ReadAllBytes
var _uploadFile = file.FileName

Related

Upload Image to Dropbox with URL

DropboxClient dbx = new DropboxClient("my_Key");
var folder = "/Apps/Images";
var file = $"fileName.jpg";
var fileToUpload = #"C:\Users\LENOVO\Test\Test\test.jpg";
using (var mem = new MemoryStream(File.ReadAllBytes(fileToUpload)))
{
var updated = await dbx.Files.UploadAsync(folder + "/" + file,
WriteMode.Overwrite.Instance,
body: mem);
Console.WriteLine("Saved {0}/{1} rev {2}", folder, file, updated.Rev);
}
i want to upload Image to Dropbox. This code is worked but i want fileToUpload to be is a web URL because images is a Web Server. i know i can download every Images step by step. But this is a loss of performance. If i write a WebUrl in the fileToUpload. i see the exception. For Example:
fileToUpload = "https:\upload.wikimedia.org\wikipedia\commons\5\51\Small_Red_Rose.JPG"
The Exception:
C:\Users\LENOVO****\bin\Debug\net6.0\https:\upload.wikimedia.org\wikipedia\commons\5\51\Small_Red_Rose.JPG
*** - is a local folder name
i want to upload image to dropbox from Web
The UploadAsync method requires that you supply the data of the file to upload directly, as you are doing in your example by retrieving the file data from the local filesystem using File.ReadAllBytes.
If you want to upload a file to Dropbox directly from a URL without downloading it to your local filesystem first, you should instead use the SaveUrlAsync method.

PdfSharp: Get PdfDocument from specified file path and name

I am using pdfsharp in a .net application and am trying to open a pdf from a specified path and file name. However, when I try this:
PdfDocument doc = PdfReader.Open(path, PdfDocumentOpenMode.Import);
Where path is the filepath and name, it is appended to the path for my project's web folder. For example, if my path is https:\site.net\files\thisfile.pdf, it will search for C:\Users\thisuser\Proj\ProjWeb\https:\site.net\files\thisfile.pdf instead.
How can I get a PdfDocument using only the path and file name I have specified, without having this additional path being appended to it?
The solution must account for multiple filepaths as the value of path is based on other conditions.
You are trying to load file from URL, while Pdfreader.Open only supports loading files locally or from a stream.
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(path);
Stream pdfstream = req.GetResponse().GetResponseStream();
PdfDocument doc = PdfReader.Open(pdfstream, PdfDocumentOpenMode.Import);
The above code will try to load the PDF from a remote url into Stream, then open the PDF from said stream. I haven't tested this, but according to this ( where the code was obtained ) https://forum.pdfsharp.net/viewtopic.php?f=2&t=2030, you might have to use MemoryStream in place of Stream.

How to create a bitmap temp file and get the path WebApi C#

I'm using a DropBox API just for tests and I need to save some images from my WebApi, the problem is I need to have a stringPath to make the upload, but since the Bitmap image will be "stored" inside of my model, I need to create a tempFile with a unique name for that image, so I could get a path and upload the image!
This is how upload :
async Task Upload(DropboxClient dbx, string folder, string file, string content)
{
using (var mem = new MemoryStream(Encoding.UTF8.GetBytes(content)))
{
var updated = await dbx.Files.UploadAsync(
folder + "/" + file,
WriteMode.Overwrite.Instance,
body: mem);
Console.WriteLine("Saved {0}/{1} rev {2}", folder, file, updated.Rev);
}
}
You have misunderstanding on path argument for UploadAsync() method.
It's not a source path to local file that you're going to upload.
It's a destination path to remote file in user's Dropbox. See Dropbox documentation for details.

Using webclient to download images from deployed website

i deployed a website on IIS running on localhost/xxx/xxx.aspx . On my WPF side , i download a textfile using webclient from the localhost server and save it at my wpf app folder
this is how i do it :
protected void DownloadData(string strFileUrlToDownload)
{
WebClient client = new WebClient();
byte[] myDataBuffer = client.DownloadData(strFileUrlToDownload);
MemoryStream storeStream = new MemoryStream();
storeStream.SetLength(myDataBuffer.Length);
storeStream.Write(myDataBuffer, 0 , (int)storeStream.Length);
storeStream.Flush();
string currentpath = System.IO.Directory.GetCurrentDirectory() + #"\Folder";
using (FileStream file = new FileStream(currentpath, FileMode.Create, System.IO.FileAccess.ReadWrite))
{
byte[] bytes = new byte[storeStream.Length];
storeStream.Read(bytes, 0, (int)storeStream.Length);
file.Write(myDataBuffer, 0, (int)storeStream.Length);
storeStream.Close();
}
//The below Getstring method to get data in raw format and manipulate it as per requirement
string download = Encoding.ASCII.GetString(myDataBuffer);
}
This is by writing btyes and saving them . But how do i download multiple image files and save it on my WPF app folder? I have a URL like this localhost/websitename/folder/designs/ , under this URL , there is many images , how do i download all of them ? and save it on WPF app folder?
Basically i want to download the contents of the folder whereby the contents are actually images.
First, the WebClient class already has a method for this. Use something like client.DownloadFile(remoteUrl, localFilePath).
See this link:
WebClient.DownloadFile Method (String, String)
Secondly, you will need to index the files you want to download on the server somehow. You can't just get a directory listing over HTTP and then loop through it. The web server will need to be configured to enable directory listing, or you will need a page to generate a directory listing. Then you will need to download the results of that page as a string using WebClient.DownloadString and parse it. A simple solution would be an aspx page that outputs a plaintext list of files in the directory you want to download.
Finally, in the code you posted you're saving every single file you download as a file named "Folder". You need to generate a unique filename for each file you want to download. When you're looping through the files you want to download, use something like:
string localFilePath = Path.Combine("MyDownloadFolder", imageName);
where imageName is a unique filename (with file extension) for that file.

how to download file from webserver when url contains only file ID

We have video clip storage and we want to provide url link to the end user for the clips so that end user can start downloading the clips by clicking on the url. But trick here is url link is not direct path to the clip file stored on the virtual folder but url contains clip ID. It might look like,
www.xyz.com/clipstore/ID
When end user click on the url, server should search for the clip in the clip storage, process the clip ( convert from one format to other format) and start download at end user location.
Can anyone please guide us how server can initiate download for the end user when url is not directly pointing to the file but ID of it.
We are using IIS 6 / 7 , C# on the server side. Client is silverlight based.
It is possible and quite straight forward in ASP.net MVC.
For the sake of example, I have hard coded the mime type to "image/png", but i should be according to file type.
public ActionResult clipstore(string id)
{
var path = GetFilePathByID(id);
StreamReader reader = new StreamReader(path);
var fileBytes = System.IO.File.ReadAllBytes(path);
FileContentResult file = File(fileBytes, "image/png");
return file;
}

Categories