gpt4 book ai didi

asp.net-mvc-3 - 如何使用 .net 将文件上传到 RackSpace 云文件?

转载 作者:行者123 更新时间:2023-12-04 03:38:30 24 4
gpt4 key购买 nike

我想使用 RackSpace 的 CDN(云文件)来存储我的静态内容。问题是我正在使用 ASP.NET MVC3 并且我还没有看到任何当前的工作示例来说明如何做到这一点。

我在网上看到了几个示例,但它们都是 RackSpace 不再支持的版本。您可以在他们的注释中确认:

http://www.rackspace.com/knowledge_center/article/sample-csharp-application-for-cloud-files

当您在 openstack.net 下查看 RackSpace 的 gitHub 帐户(他们的支持重定向到该项目)时,您会发现不支持将文件上传到 Cloud Files。您可以在"file"表下看到:

https://github.com/rackspace/openstack.net/wiki/Feature-Support

如何使用 C# 以编程方式将文件上传到 RackSpace 的云文件?

最佳答案

您是对的,目前 openstack.net 项目不支持 CloudFiles。该功能计划于本月晚些时候(4 月中旬)发布。如果您愿意,您仍然可以使用 csharp-cloudfiles ( https://github.com/rackerlabs/csharp-cloudfiles ),因为它仍然有效,它只是处于弃用状态,不会收到任何更新或错误修复。

但是,这是一个快速但不完善的控制台应用程序,它使用内置的 HttpWebRequest/Response 对象,应该可以帮助您入门,直到 openstack.net v1.1 发布。

class Program
{
const string filePath = @"Path\FileName";
const string myToken = "myToken";
const string url = "Url/Container/FileName";

static void Main(string[] args)
{
//Do();
DoAsync();
}

static void Do()
{
using (var fs = File.Open(filePath, FileMode.Open, FileAccess.Read))
{
UploadStream(new Uri(url), fs, myToken,
(response) => Console.WriteLine("Upload Complete. Status Code: {0} ({1})", response.StatusCode, response.StatusDescription));
}

Console.WriteLine("Done!");
Console.ReadLine();
}

static void DoAsync()
{
IAsyncResult asyncRes;
using (var fs = File.Open(filePath, FileMode.Open, FileAccess.Read))
{
asyncRes = UploadStreamAsync(new Uri(url), fs, myToken,
(asyncResult) =>
{
var request = (HttpWebRequest)asyncResult.AsyncState;
var response = (HttpWebResponse)request.EndGetResponse(asyncResult);
Console.WriteLine("Upload Complete. Status Code: {0} ({1})", response.StatusCode, response.StatusDescription);
});
}

asyncRes.AsyncWaitHandle.WaitOne();

Console.WriteLine("Done!");
Console.ReadLine();
}

static IAsyncResult UploadStreamAsync(Uri uri, Stream contents, string token, AsyncCallback resultCallback, int chunkSize = 8 * 1024)
{
var req = (HttpWebRequest)WebRequest.Create(uri);
req.Headers.Add("X-Auth-Token", token);
req.Method = "PUT";

req.AllowWriteStreamBuffering = false;
if (req.ContentLength == -1L)
req.SendChunked = true;

using (Stream stream = req.GetRequestStream())
{
var buffer = new byte[chunkSize];
int count;
while ((count = contents.Read(buffer, 0, chunkSize)) > 0)
{
stream.Write(buffer, 0, count);
}
}

return req.BeginGetResponse(resultCallback, req);
}

static void UploadStream(Uri uri, Stream contents, string token, Action<HttpWebResponse> resultCallback, int chunkSize = 8 * 1024)
{
var req = (HttpWebRequest)WebRequest.Create(uri);
req.Headers.Add("X-Auth-Token", token);
req.Method = "PUT";

req.AllowWriteStreamBuffering = false;
if (req.ContentLength == -1L)
req.SendChunked = true;

using (Stream stream = req.GetRequestStream())
{
var buffer = new byte[chunkSize];
int count;
while ((count = contents.Read(buffer, 0, chunkSize)) > 0)
{
stream.Write(buffer, 0, count);
}
}

using (var resp = req.GetResponse() as HttpWebResponse)
{
resultCallback(resp);
}
}
}

在上面的代码中,我同时提供了 Async 和 Synchronous 方法,因此您不需要两者,只需使用最适合您的方法即可。

如果您安装了 Http 客户端 NuGet 包 ( http://nuget.org/packages/Microsoft.Net.Http/2.0.20710.0 ),您也可以使用 HttpClient 库。这是一个示例:

static void UploadFileToRSCloud(string path, string filename)
{
HttpClient client = new HttpClient();
MemoryStream ms = new MemoryStream();

client.DefaultRequestHeaders.TransferEncodingChunked = true;

var filePath =
// Copy the data to the Resource Part
using (FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
CopyStream(fileStream, ms);
}// end:using(fileStream) - Close and dispose fileStream.

ms.Position = 0;
StreamContent sc = new StreamContent(ms);

client.DefaultRequestHeaders.Add("X-Auth-Token", "TOKEN HERE");

var result = client.PutAsync( "UrlBase/Container/ChipperJones.jpg", sc);

result.Wait();
}

private static void CopyStream(Stream source, Stream target)
{
const int bufSize = 0x1000;
byte[] buf = new byte[bufSize];
int bytesRead = 0;
while ((bytesRead = source.Read(buf, 0, bufSize)) > 0)
target.Write(buf, 0, bytesRead);
}

希望对您有所帮助!

关于asp.net-mvc-3 - 如何使用 .net 将文件上传到 RackSpace 云文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15711361/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com