简体   繁体   中英

Upload to Google Drive using API C# from web user

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM