我正在将图像上传到ASP WebAPI服务,然后将其上传到windows azure。一切都很好但突然间我开始得到以下异常:
System.IO.IOException: The process cannot access the file
'C:\DWASFiles\Sites\Tasteat\Temp\BodyPart_a5c79910-6077-4c24-b814-10fdc0e0b3d4'
because it is being used by another process.
这是抛出异常的代码:
var provider = new BlobStorageProvider(container);
Trace.TraceInformation("Uploading raw image to blob");
await Request.Content.ReadAsMultipartAsync(provider);
Trace.TraceInformation("Uploading finished");
我知道它的这一行await Request.Content.ReadAsMultipartAsync(provider);
因为我在日志中看到它前面的行而不是它后面的行。
有什么想法吗?
一切都很好,直到几天
答案 0 :(得分:1)
因此,我上面发布的代码似乎实际上保存了一个本地文件,然后才将其上传到服务器,这会导致错误,但也很慢。 经过大量的尝试后,我终于改用以下解决方案,一切都开始工作,甚至更快!
首先创建一个streamprovider:
public class BlobStorageMultipartStreamProvider : MultipartStreamProvider
{
private readonly string _containerName;
private readonly string _fileName;
public BlobStorageMultipartStreamProvider(string containerName, string fileName)
{
_containerName = containerName;
_fileName = fileName;
}
public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
{
Stream stream = null;
if (!String.IsNullOrWhiteSpace(_fileName))
{
string connectionString = ConfigurationManager.ConnectionStrings["BlobStorage"].ConnectionString;
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer blobContainer = blobClient.GetContainerReference(_containerName);
CloudBlockBlob blob = blobContainer.GetBlockBlobReference(_fileName);
stream = blob.OpenWrite();
}
return stream;
}
}
上传代码:
string fileName = Guid.NewGuid()+".Png";
MultipartStreamProvider provider = new BlobStorageMultipartStreamProvider("container",fileName);
Trace.TraceInformation("Uploading raw image to blob");
await Request.Content.ReadAsMultipartAsync(provider);
Trace.TraceInformation("Uploading finished");