We are currently uploading a photo to a WebMethod
via javascript
everything works perfectly fine on local.
Yet when I deploy this to staging we get the following exception: System.IO.FileNotFoundException
Our javascript
method is as follows:
var formData = new FormData();
formData.append('file', $('#photo')[0].files[0]); // Image
formData.append('c', i);
formData.append('t', t);
formData.append('i', uuid);
$.ajax({
url: "/member/myserice/test.asmx/UploadImage",
type: "POST",
processData: false,
contentType: false,
data: formData,
success: function (response) {
alert('success');
},
error: function (er) {
alert('Unable to upload photo at this time, please try again later');
}
});
Now as you can see we store the uploaded image inside formData (first parameter)
Our WebMethod
is as follows:
public string UploadImage()
{
var httpRequest = HttpContext.Current.Request;
var timestamp = httpRequest.Form["t"];
var consumerId = httpRequest.Form["c"];
var guid = httpRequest.Form["i"];
var pic = System.Web.HttpContext.Current.Request.Files["file"];
string fileName = Path.GetFileName(pic.FileName); // Breaks here when deployed to staging
var img = System.Drawing.Image.FromFile(pic.FileName);
//Removed additional code as it calls an external API.
}
Now as mentioned before this works perfectly fine on local, yet when deployed to staging I get the exception System.IO.FileNotFoundException
on the following line:
string fileName = Path.GetFileName(pic.FileName);
Now I've tried searching the web for a given solution or an detailed explanation into why and how to fix but with no avail, can someone shed some light into what if needs be I need change to get this to function correctly.
Thanks in advance.
This works locally because both client and server use the same file system and path from $('#photo')[0].files[0]
point to same file on server. You shouldn't try to read file from file system on server side, but use the file stream from HttpContext
Instead of
var pic = System.Web.HttpContext.Current.Request.Files["file"];
string fileName = Path.GetFileName(pic.FileName); // Breaks here when deployed to staging
var img = System.Drawing.Image.FromFile(pic.FileName);
Use the file stream uploaded from client:
var pic = System.Web.HttpContext.Current.Request.Files["file"];
var img = System.Drawing.Image.FromStream(pic.InputStream);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.