【发布时间】:2020-04-14 02:36:03
【问题描述】:
我有一个视图,我通过 ajax 将数据发送到 MVC 中的一个操作。我只想在任务完成时在视图中收到通知。我遇到的问题是我之前是否收到通知,或者如果我等到任务完成我的视图被阻止。这是我所做的一个例子:
function UploadFile(file) {
$.ajax({
url: '/Home/Upload',
type: 'POST',
data: file,
success: function (result) {
alert(result);
}
});
}
[HttpPost]
public async Task<ActionResult> Upload(httpPostedFileBase file)
{
NewFile service = new NewFile((long)Session["UserId"]);
Thread thread = new Thread(() =>service.UploadFile(file));
thread.Start();
return Json("File Uploaded", JsonRequestBehavior.AllowGet);
}
public async Task<string> UploadFile(HttpPostedFileBase file) // returns the file Id in Google Drive
{
Google.Apis.Drive.v3.Data.File uploadedFile = new Google.Apis.Drive.v3.Data.File();
try
{
if (file != null && file.ContentLength > 0)
{
// Check for credentials
Google.Apis.Drive.v3.DriveService service = Service;
// Uploads the file to the server in "~/GoogleDriveFiles" folder.
/*string path = Path.Combine(HttpContext.Current.Server.MapPath("~/GoogleDriveFiles"),*/ // TODO Doesn't work with Unit testing. Must be written manual for testing
//Path.GetFileName(file.FileName));
//file.SaveAs(path);
// Save the metadata of the file
var FileMetaData = new Google.Apis.Drive.v3.Data.File()
{
Name = Path.GetFileName(file.FileName),
MimeType = MimeMapping.GetMimeMapping(file.FileName),
Parents = new List<string>
{
GetReposFolderId()
}
};
// Create a request for upload
Google.Apis.Drive.v3.FilesResource.CreateMediaUpload request;
file.InputStream.Close();
// Create a stream using the file filepath and filling the request. Then upload.
using (var stream = new System.IO.FileStream(file.FileName, System.IO.FileMode.Open))
{
request = service.Files.Create(FileMetaData, stream, FileMetaData.MimeType);
request.Fields = "id";
await request.UploadAsync();//TODO Tuka bavi i ne mozesh da browswash prez papkite dokato ne go kachi na servara
}
uploadedFile = request.ResponseBody;
}
}
catch (Exception ex)
{
ErrorEngine.RuntimeExceptions runtimeExceptions = new ErrorEngine.RuntimeExceptions();
runtimeExceptions.ManageException(ex, this);
return ex.ToString();
}
return uploadedFile.Id;
}
我对 MVC 和一般编码方面的经验并不如您想象的那样。你能帮我解决这个问题吗?
【问题讨论】:
-
您应该永远调用
new Thread(...),除非您正在编写自定义线程调度程序。您应该改用Task.Run(...)。
标签: c# asp.net ajax asp.net-mvc asynchronous