我知道必须有更好的方法来做到这一点,但我有一个解决方案,至少可以工作。如果任何人都可以指出一个更复杂的方式,我全部耳朵。我会假设有某种对象会在服务器上接收到保存到磁盘的img,但也许不会。
Javascript和webmethod保持不变。我将div的InnerHTML传递给服务器,并将其作为字符串接受。在服务器上,我使用了多个分割(我知道它非常慢)以获取图像的base64部分。
[WebMethod]
public static string uploadImage(string base64FileString){
//Get all of the text right of the comma
string base64PartTemp= base64FileString.Split(',')[1];
//The final part of the base64 had a \" to remove
//Now base64PartFinal is the base64 part of the image only
string base64PartFinal= base64PartTemp.Split('\"')[0];
//Get all of the text to the right of the period from original string
string fileTypePart = base64FileString.Split('.')[1];
//Because the file is an image the file type will be 3 chars
string fileType = fileTypePart.Substring(0, 3);
//Use a new guid for the file name, and append the fileType
string finalFileName = Guid.NewGuid() + "." + fileType;
//Turn the final base64 part into byte array
byte[] imageBytes = Convert.FromBase64String(base64PartFinal);
//Get the working directory of the project to store the files
string path= System.AppDomain.CurrentDomain.BaseDirectory.ToString();
//Append that I want to put the image in the images folder, under a designated filename
path += "Images/" + finalFileName;
//Write the image to file
File.WriteAllBytes(path, imageBytes);
...
}
我几天没找到答案。我希望它能帮助别人。就像我说的,可能不是最有效的解决方案,但它确实有效。