【发布时间】:2019-06-08 19:28:47
【问题描述】:
我正在尝试部署一个网站,但我的一个上传图片的表单出现错误。
首先,我使用 NetworkSolutions 进行托管,其中一种形式具有图像文件上传输入。当我在本地运行应用程序并将图像上传到 FTP 时,一切正常,但是当我部署到服务器时,连接似乎超时(因为它挂了一会儿),而不是我收到消息 "对象引用未设置为对象的实例。”。我应该注意的一件事是此服务器上没有设置 SSL,但是我使用的是不安全的端口。
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Submit(RegistrationViewModel viewModel)
{
if (!ModelState.IsValid)
{
return RedirectToAction("Index", viewModel);
}
if (Request.Files.Count > 0)
{
string path = String.Empty;
HttpPostedFileBase file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
string fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName); // Path.GetFileName(file.FileName);
try
{
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential("***", "***");
byte[] buffer = new byte[file.ContentLength];
file.InputStream.Read(buffer, 0, buffer.Length);
file.InputStream.Close();
path = "ftp://***.***.com:21/pics/" + fileName;
client.UploadData(path, buffer);
}
}
catch (WebException ex)
{
string status = ((FtpWebResponse)ex.Response).StatusDescription;
}
}
Context.Registrations.Add(new Registration
{
FirstName = viewModel.FirstName,
LastName = viewModel.LastName,
Email = viewModel.Email,
PhoneNumber = viewModel.PhoneNumber,
Age = viewModel.Age,
ImagePath = path,
CreatedDate = DateTime.Now
});
await Context.SaveChangesAsync();
ConfirmationViewModel confirmViewModel = new ConfirmationViewModel
{
FirstName = viewModel.FirstName,
LastName = viewModel.LastName,
Email = viewModel.Email,
PhoneNumber = viewModel.PhoneNumber
};
return RedirectToAction("Confirm", "Register", confirmViewModel);
}
}
我希望图像应该像在本地一样保存到路径中,但是在服务器上我无法通过此超时/空异常。堆栈跟踪中的异常是当方法 UploadData 在寄存器控制器第 89 行中命中时(我在寄存器控制器中显示了提交函数)。由于此问题发生在服务器上,因此获得有关错误的反馈相当有限。删除 try/catch 我得到内部服务器错误,使用 try catch,我得到 Null 引用异常。
我尝试过的一件事是假设这里的某些内容为空,但结果相同:
file.InputStream.Read(buffer, 0, buffer.Length);
file.InputStream.Close();
任何帮助将不胜感激。
【问题讨论】:
-
您必须提供有关异常的更多详细信息以及代码中断的行号...!
-
更新了原帖。 “堆栈跟踪中的异常是当方法 UploadData 命中时,在寄存器控制器第 89 行(我在寄存器控制器中显示了提交函数)”
-
我继续测试。我尝试使用具有完全管理员权限的主 FTP 帐户,但发生了同样的问题。我尝试写入网站所在的目录而不是通过 FTP,但出现访问被拒绝错误。所以看来我仅限于通过 FTP。这个问题已经持续了很长一段时间,每次我尝试在服务器上测试时,每次至少需要 10 分钟才能发布。
标签: c# model-view-controller ftp upload webclient