How to get the modified uploaded file name in server side while delete a file?
How to modify uploaded file name and delete the modified file in Uploadbox?
Description
In the UploadBox save process, let us assume that a file is uploaded to server and after some modifications, save the file with another name in the server. Now when that file is required to be deleted from the server using the UploadBox, it cannot be done using the old name. So, the modified name from the server is required during the file delete process.
Solution
To get started with this example, refer to the Getting Started section in the Uploadbox’s UG documentation and create a basic UploadBox example.
In the Save handler, the uploaded file name is altered and saved in a location in the server. Now that is done, the updated name along with original name is returned to the UploadBox as a JSON. Refer to the following code.
public ActionResult SaveDefault(IEnumerable<HttpPostedFileBase> UploadDefault) { foreach (var file in UploadDefault) { var fileName = Path.GetFileNameWithoutExtension(file.FileName) + "_" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + Path.GetExtension(file.FileName); fileName = fileName.Replace(' ', '_'); string path = Server.MapPath("~/App_Data"); if (Directory.Exists(path) == false) { Directory.CreateDirectory(path); } var destinationPath = Path.Combine(Server.MapPath("~/App_Data"), fileName); List<uploadFile> Uploadfiles = new List<uploadFile>(); Uploadfiles.Add(new uploadFile { oldname = file.FileName, newname = fileName }); file.SaveAs(destinationPath); return Json(Uploadfiles); } return Content(""); } public class uploadFile{ public string oldname { get; set; } public string newname { get; set; } }
The client-side “Success” event will be triggered when each upload action is successful. In that event, the JSON returned from the server with the modified file name can be accessed and added as a new attribute to the span element of the corresponding li element. Refer to the following code:
var txtArray; function success(args) { txtArray = JSON.parse(args.responseText); $($(args.files).data("filelist").find(".e-file-name-txt")[0]).attr("data-newname", txtArray[0].newname) }
After the new name is added to the uploadbox as an attribute, some changes in the UploadBox’s internal _xhrOnRemove method are required to access the new name instead of the old value. Refer to the following code.
var bool=false; var filename; ej.Uploadbox.prototype.remove = ej.Uploadbox.prototype._xhrOnRemove; ej.Uploadbox.prototype._xhrOnRemove = function (e, fileItem) { var filename = fileItem.find(".e-file-name-txt").attr("data-newname"), proxy = this; $.ajax({ url: this.model.removeUrl, type: "POST", data: "fileNames=" + filename, success: function () { $(fileItem).remove(); proxy._fileListRemove(); proxy._trigger("remove", { fileStatus: proxy._file }); } }); }