我使用远程云服务器来存储我的图像。如果我使用控制台执行这些代码,它运行良好,但在asp.net mvc中它总是挂在" WaitOne() "
public class UploadUtil
{
public static string UploadBase64(string bucket,string filelocation)
{
//qiniu.Config.ACCESS_KEY = System.Configuration.ConfigurationManager.AppSettings["ACCESS_KEY"];
//qiniu.Config.SECRET_KEY = System.Configuration.ConfigurationManager.AppSettings["SECRET_KEY"];
qiniu.Config.InitFromAppConfig();
string qiniuKey = Guid.NewGuid().ToString();
string returnUrl = string.Empty;
ManualResetEvent done = new ManualResetEvent(false);
jpegToBase64 jpeg = new jpegToBase64(filelocation);
QiniuFile qfile = new QiniuFile(bucket, qiniuKey);
qfile.UploadCompleted += (sender, e) => {
returnUrl = e.RawString;
Console.Write(e.RawString);
done.Set();
};
qfile.UploadFailed += (sender, e) => {
QiniuWebException qe = (QiniuWebException)e.Error;
Console.WriteLine(qe.Error.ToString());
};
qfile.UploadString((int)jpeg.Filesize, "image/png", jpeg.Base64Content);
done.WaitOne();
return returnUrl;
}
}
actionresult看起来像这样,如果我使用正常的ActionResult,就会发生错误,所以我必须使用Task
public Task<ActionResult> TestUpload()
{
var s = UploadUtil.UploadBase64("kmsfan", @"D:\\b.jpg");
return null;
}
答案 0 :(得分:4)
如果上传失败,您的ManualResetEvent将永远不会发出信号。您应该避免在服务器环境中阻止同步代码。
使用TaskCompletionSource表示您的异步上传任务:
public class UploadUtil
{
public static Task<string> UploadBase64Async(string bucket,string filelocation)
{
var tcs = new TaskCompletionSource<string>();
qiniu.Config.InitFromAppConfig();
string qiniuKey = Guid.NewGuid().ToString();
jpegToBase64 jpeg = new jpegToBase64(filelocation);
QiniuFile qfile = new QiniuFile(bucket, qiniuKey);
qfile.UploadCompleted += (sender, e) => {
var returnUrl = e.RawString;
Console.Write(returnUrl);
tcs.SetResult(returnUrl);
};
qfile.UploadFailed += (sender, e) => {
QiniuWebException qe = (QiniuWebException)e.Error;
Console.WriteLine(qe.Error.ToString());
tcs.SetException(qe);
};
qfile.UploadString((int)jpeg.Filesize, "image/png", jpeg.Base64Content);
return tcs.Task;
}
}
控制器:
public async Task<string> TestUpload()
{
var s = await UploadUtil.UploadBase64Async("kmsfan", @"D:\\b.jpg");
return s;
}