Problem
Since programming, I have not used the input [type = file] control for the moment. Today I suddenly used the control and reported an error. It is good for other browsers such as chrome and firefox locally, but ie reported an error. Chrome also reports an error on the server.
Cause
The main cause of this error is that when uploading images locally, the FileName saved in the HttpPostedFileBase object is only the file name.
When deploying a server, uploading FileName is the physical path of your local upload, that is, the complete local path, as shown in figure
Solve the problem
Therefore, when we execute the following code, an error is reported.
FileName = imgLogo. FileName; string type = fileName. Substring (fileName. LastIndexOf (".") + 1). ToLower (); if (! ValidateImg (type) {ErrorModel errorModel = new ErrorModel ("imgLogo", "only image files can be uploaded! "); ViewBag. errorModel = errorModel; return View (config) ;}// full path strength, resulting in the server. the Server path obtained by mappath is actually incorrect, so the following saveas will directly report the error var path = Server. mapPath ("~ /Images/"+ fileName); imgLogo. SaveAs (path );
Now that you know the reason, it is easy to solve the problem. Just take a look at the fileName. The Code is as follows:
// Just extract the file name here. fileName = imgLogo. fileName. substring (imgLogo. fileName. lastIndexOf ("\") + 1); string type = fileName. substring (fileName. lastIndexOf (". ") + 1 ). toLower (); if (! ValidateImg (type) {ErrorModel errorModel = new ErrorModel ("imgLogo", "only image files can be uploaded! "); ViewBag. errorModel = errorModel; return View (config) ;}// full path strength, resulting in the server. the Server path obtained by mappath is actually incorrect, so the following saveas will directly var path = Server. mapPath ("~ /Images/"+ fileName); imgLogo. SaveAs (path );