c# - How to call a .net method in AJAX on fileupload change? -
i'm trying upload file using ajax problem i'm rookie in .net , don't know if did right or not appreciate or suggestions.
here html code:
<asp:fileupload id="fileupload1" onchange="show()" runat="server" />
my method should called when users selects file
this script found in msdn:
<script type="text/javascript"> function show() { var file = document.getelementbyid("fileupload1"); alert("test") $.ajax({ type: "post", url: "sendsms.aspx/staticupdate", data: '{name:"test" }', contenttype: "application/json; charset=utf-8", datatype: "json", success: onsuccess, failure: function (response) { alert("test1"); } }); } function onsuccess(response) { alert("test2"); } </script>
and here asp method:
[system.web.services.webmethod] public static void staticupdate() { sendsms upload = new sendsms(); upload.upload(); } public void upload() { string filename = system.datetime.now.tostring("ddmmyyhhmmsss") + fileupload1.filename; if (ispostback) { boolean fileok = false; string path = server.mappath("~/upload/"); if (fileupload1.hasfile) { string fileextension = system.io.path.getextension(filename).tolower(); string[] allowedextensions = { ".txt" }; (int = 0; < allowedextensions.length; i++) { if (fileextension == allowedextensions[i]) { fileok = true; } } } if (fileok) { try { fileupload1.postedfile.saveas(path + filename); system.io.streamreader myfile = new system.io.streamreader("c:\\inetpub\\wwwroot\\viber_bulk_ui\\upload\\" + filename + ""); textbox2.text = myfile.readtoend(); myfile.close(); string path = "c:\\inetpub\\wwwroot\\viber_bulk_ui\\upload\\" + filename + ""; system.io.file.delete(path); } catch (exception ex) { label1.text = "file not uploaded."; } } else { label1.text = "cannot accept files of type."; } } }
the error this:
nullreferenceexception unhandled user code. object reference not set instance of object.
thanks in advance
string filename = system.io.path.getfilename(fileupload1.filename); string ext = system.io.path.getextension(fileupload1.filename); if (fileextension == ".txt"){ using (system.io.filestream fs = new system.io.filestream(server.mappath(("c:\\inetpub\\wwwroot\\viber_bulk_ui\\upload\\" + filename), system.io.filemode.append, system.io.fileaccess.write, system.io.fileshare.read, 8, system.io.fileoptions.none)) { byte[] data = system.text.encoding.ascii.getbytes(filename); fs.write(data, 0, data.length); fs.flush(); fs.close(); } }
Comments
Post a Comment