this post will help you to upload a file to the server with a new name
HTML
<form>
<input type="file" id="filelogo" class="fileUpload" accept="image/x-png,image/jpeg" /><br /><br />
<input type="button" value="Upload" onclick="UploadImage('filelogo','new name')" >
</form>
Java Script
function UploadImage(fnm,newname)
{
var data = new FormData();
data.append("filename", $("#"+fnm)[0].fil
es[0]);
var name = document.getElementById(fnm);
var fname = name.files.item(0).name;
var fileExtension = fname.split('.').pop();
$.ajax({
url: '/WebsiteAdmin/UploadAssociateLogo?fnm=' + newname + "&pth=~/AppImage/AssociateLogo/",
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: data,
success: function (result) {
if (result == "1") {
alert("Image Uploaded Successfully");
window.location = "javascript:history.back()";
}
},
error: function (abc) {
alert(abc.statusText);
}
});
}
Controller
[HttpPost]
public JsonResult UploadAssociateLogo(string fnm, string pth)
{
if (Request.Files.Count > 0)
{
try
{
// Get all files
from Request object
HttpFileCollectionBase files =
Request.Files;
for (int i = 0; i <= files.Count - 1; i++)
{
HttpPostedFileBase file =
files[i];
string fname =
files[0].FileName;
string fileName = fnm;
string fileExtension = Path.GetExtension(fname);
fname = fileName + fileExtension;
// Get the complete folder path and store the file inside
it.
fname = Path.Combine(Server.MapPath(pth),
fname);
file.SaveAs(fname);
}
// Returns message that successfully uploaded
var msg = "1";
return Json(msg, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json("Error occurred. Error details: " + ex.Message);
}
}
else
{
return Json("No files
selected.");
}
}
No comments:
Post a Comment