我正在尝试使用 C# 将图像上传到我的谷歌驱动器。如果我想上传到根目录,此代码可以正常工作。 但我想将图像上传到云端硬盘中的特定文件夹。 需要建议。
private static void UploadBasicImage(string file_path,DriveService service)
{
var fileMetadata = new Google.Apis.Drive.v3.Data.File();
fileMetadata.Name = Path.GetFileName(path);
fileMetadata.MimeType = "image/png";
FilesResource.CreateMediaUpload request;
using (var stream = new System.IO.FileStream(path,System.IO.FileMode.Open))
{
request = service.Files.Create(fileMetadata, stream, fileMetadata.MimeType);
request.Fields = "id";
request.Upload();
}
var file = request.ResponseBody;
}
这是我刚刚想出的解决方案:
完整详情在这里
public static void FileUploadInFolder(string folderId, string path, DriveService service)
{
var FileMetaData = new Google.Apis.Drive.v3.Data.File()
{
Name = Path.GetFileName(path),
MimeType = GetMimeType(path),
//id of parent folder
Parents = new List<string>
{
folderId
}
};
FilesResource.CreateMediaUpload request;
//create stream and upload
using (var stream = new System.IO.FileStream(path, System.IO.FileMode.Open))
{
request = service.Files.Create(FileMetaData, stream, FileMetaData.MimeType);
request.Fields = "id";
request.Upload();
}
var file1 = request.ResponseBody;
}
我只想添加响应中缺少的 GetMimeType(path) 的代码:
private string GetMimeType(string filePath)
{
string mimeType = "application/unknown";
string ext = System.IO.Path.GetExtension(filePath).ToLower();
Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
if (regKey != null && regKey.GetValue("Content Type") != null)
mimeType = regKey.GetValue("Content Type").ToString();
return mimeType;
}
此线程中还有其他解决方案: 从文件扩展名获取 MIME 类型