I have the following client side function:
function UploadFile() {
var formData = new FormData();
var file = document.getElementById("file").files[0];
formData.append("file", file);
var uploadServerSideScriptPath = "Login.aspx/Img_Upload";
var xhr = new XMLHttpRequest();
xhr.open("POST", uploadServerSideScriptPath, true);
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("X-File-Type", file.type);
xhr.send(formData);
}
the server-side is:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void Img_Upload()
{
HttpContext postedContext = HttpContext.Current;
HttpPostedFile file = postedContext.Request.Files[0];
string name = file.FileName;
byte[] binaryWriteArray = new
byte[file.InputStream.Length];
file.InputStream.Read(binaryWriteArray, 0,
(int)file.InputStream.Length);
FileInfo file_Info = new FileInfo(file.FileName);
string ext = file_Info.Extension;
string file_Name = Guid.NewGuid().ToString() + "_" + DateTime.Now.Day + DateTime.Now.Month + DateTime.Now.Year + ext;
FileStream objfilestream = new FileStream(Server.MapPath("img//profilePIC//" + file_Name), FileMode.Create, FileAccess.ReadWrite);
objfilestream.Write(binaryWriteArray, 0,
binaryWriteArray.Length);
objfilestream.Close();
}
I put a break-point inside Img_Upload but it never hits. I used fiddler and the request seems ok. any ideas why?
If I use var uploadServerSideScriptPath = "Login.aspx", I get to the page_load function. The problem is to call a specific method on that page.
Try clientID for getElementByID() method as
...
function UploadFile() {
var formData = new FormData();
var file = document.getElementById("<%=file.ClientID%>").files[0];
...
我通过创建.axd处理程序并使用ProcessRequest解决了该问题
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.