如何解决将媒体文件上载到4 MB以上的Azure文件共享会损坏它们
我正在尝试通过Azure.Storage.Files.Shares
库将大文件上传到Azure文件共享,我在大约4 MB以上的所有媒体文件(图像,PDF等)中遇到损坏问题。 Azure文件共享对单个请求的限制为4 MB,这就是为什么我将上传分为多个块的原因,尽管每个块上传都返回201,但它仍然会损坏文件。
注意:
此功能的此上载部分基本上是从我发现的有关此问题的唯一其他堆栈溢出“解决方案”中复制/粘贴的:
public async Task WriteFileFromStream(string fullPath,MemoryStream stream)
{
// Get pieces of path
string dirName = Path.GetDirectoryName(fullPath);
string fileName = Path.GetFileName(fullPath);
ShareClient share = new ShareClient(this.ConnectionString,this.ShareName);
// Set position of the stream to 0 so that we write all contents
stream.Position = 0;
try
{
// Get a directory client for specified directory and create the directory if it doesn't exist
ShareDirectoryClient directory = share.GetDirectoryClient(dirName);
directory.CreateIfNotExists();
if (directory.Exists())
{
// Get file client
ShareFileClient file = directory.GetFileClient(fileName);
// Create file based on stream length
file.Create(stream.Length);
int blockSize = 300 * 1024; // can be anything as long as it doesn't exceed 4194304
long offset = 0; // Define http range offset
BinaryReader reader = new BinaryReader(stream);
while (true)
{
byte[] buffer = reader.ReadBytes(blockSize);
if (buffer.Length == 0)
break;
MemoryStream uploadChunk = new MemoryStream();
uploadChunk.Write(buffer,buffer.Length);
uploadChunk.Position = 0;
HttpRange httpRange = new HttpRange(offset,buffer.Length); // offset -> buffer.Length-1 (inclusive)
var resp = file.UploadRange(httpRange,uploadChunk);
Console.WriteLine($"Wrote bytes {offset}-{offset+(buffer.Length-1)} to {fullPath}. Response: {resp.GetRawResponse()}");
offset += buffer.Length; // Shift the offset by number of bytes already written
}
reader.Close();
}
else
{
throw new Exception($"Failed to create directory: {dirName}");
}
}
catch (Exception e)
{
// Close out memory stream
throw new Exception($"Error occured while writing file from stream: {e.Message}");
}
}
对此表示任何帮助。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。