c# - Uploading Document to App_Data -
i've got working code upload document app_data file, need able differentiate files uploaded if have same name. want modifying file name so: id" "filename
i've had few attempts include in object thats passed controller can't find stored anywhere (i presume gets stripped out when being passed?).
here current code:
var files = $('#txtuploadfile')[0].files; if (files.length > 0) { if (window.formdata !== undefined) { var data = new formdata(); (var x = 0; x < files.length; x++) { data.append("file" + x, files[x]); } // data.uploadname = task.id + " " + files[0].name; // file.filename = id + " " + file.filename; $.ajax({ type: "post", url: '../document/uploadfiles/', contenttype: false, processdata: false, //data: {'id': (nextref + 1), 'filelocation': files[0].name }, // doesn't work data: data, // works without other variables datatype: "json", success: function (result) { //alert(result); }, error: function (xhr, status, p3, p4) { var err = "error " + " " + status + " " + p3 + " " + p4; if (xhr.responsetext && xhr.responsetext[0] == "{") err = json.parse(xhr.responsetext).message; alert(log(err)); } }); } else { alert("this browser doesn't support html5 file uploads!"); } } [httppost] public jsonresult uploadfiles()//string id, string filelocation) { try { foreach (string file in request.files) { var hpf = request.files[file] httppostedfilebase; if (hpf.contentlength == 0) continue; var filecontent = request.files[file]; if (filecontent != null && filecontent.contentlength > 0) { // stream var stream = filecontent.inputstream; // , optionally write file disk var filename = path.getfilename(file); var path = path.combine(server.mappath("~/app_data/"), path.getfilename(hpf.filename)); // save file hpf.saveas(path); } } } catch (exception) { response.statuscode = (int)httpstatuscode.badrequest; return this.json("upload failed"); } return this.json("file uploaded successfully"); }
your html should be
<div><input type="file" name="uploadfile" id="fileupload" class="fileupload" /> </div>
your ajax call should
$.ajax({ type: "post", url: '/mycontroller/uploadfiles?id=' + myid, contenttype: false, processdata: false, data: data, success: function(result) { console.log(result); }, error: function (xhr, status, p3, p4){ });
//and controller
[httppost] public jsonresult uploadfiles(string id) { // whatever want id }
happy coding...
Comments
Post a Comment