我正在创建一个api,它将从cordova文件传输插件接收文件。但在上传时,我们收到错误" [10/19/2016 5:03:33 PM] azad singh:E / FileTransfer: {"目标":" HTTP://54.252.109.57:1031 / API /客户端/ SaveDocument"" HTTP_STATUS" 500"主体&# 34;:" \"对象引用未设置为对象的实例。\"","代码":1, [10/19/2016 5:03:45 PM] azad singh:Cordova - Camera"
[HttpPost]
[Route("Uploadfile")]
public string Uploadfile()
{
string msg = "";
try
{
HttpPostedFile file = HttpContext.Current.Request.Files["file"];
string saveFile = file.FileName;
//code to save the file
msg = "File uploaded";
}
catch (Exception ex)
{
msg = "Could not upload file: " + ex.Message;
}
return msg;
}
请告诉我我的代码中缺少的地方......
答案 0 :(得分:0)
此代码适用于我......
[HttpPost]
[Route("Uploadfile")]
public UploadFile Uploadfile()
{
HttpPostedFile file = HttpContext.Current.Request.Files["file"];
UploadFile uploadedfile = new UploadFile();
//HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Accepted);
try
{
if (file == null)
return uploadedfile ;
//response = Request.CreateResponse(HttpStatusCode.NotFound, "");
int count; int sum = 0;
byte[] buffer = new byte[file.ContentLength];
int length = (int)file.InputStream.Length;
buffer = new byte[length];
while ((count = file.InputStream.Read(buffer, sum, length - sum)) > 0)
sum += count;
FileVM fileObj = new FileVM();
NameValueCollection parameters = HttpContext.Current.Request.Params;
if (parameters.Keys.Count > 0)
{
fileObj.fileId = "";
fileObj.fileName = file.FileName.ToString();
fileObj.fileType = file.ContentType;
fileObj.filedata = "";
fileObj.LastDownLoad = parameters.GetValues("LastDownLoad")[0];
ServicecltClients srv = new ServicecltClients();
uploadedfile.FileId = srv.InsertDocumentAndRelatedClient(fileObj, buffer);
uploadedfile.FileType = fileObj.fileType;
//response = Request.CreateResponse<UploadFile>(HttpStatusCode.OK, uploadedfile);
}
}
catch (Exception _ex)
{
//response = Request.CreateResponse(HttpStatusCode.InternalServerError, _ex.Message);
ErrorLog.TraceErrorLog(_ex);
}
finally
{
file.InputStream.Close();
}
return uploadedfile;
}