问题描述
我正在尝试通过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 (将#修改为@)