Upload file with text using AJAX & ASP.NET - javascript

I am having trouble uploading a file and value from a textbox/textarea in a single AJAX post. The entire project was created with AJAX posts to send data and receive resulting html/data. This means every button is handled with javascript/jquery and not asp.net's default onClick. Searches online yield answers with file upload but none of them show or explain any way to pass other parameters/data along with it.
*EDIT - I am not receiving any specific errors or crash attempting this. I try to run the file upload code in the success of the note upload or vice versa. It doesn't seem to be able to run both even if I switch it to asynchronous. I am more trying to get ONE single AJAX post to send both the file and the note to be handled in one codebehind function.
*EDIT(due to duplicate flag) - This is ASP.NET, not php. Please fully read questions before jumping to duplicate/closed conclusions.
Below is code/example of what I have so far.
HTML :
<div id="Modal_New_Document" class="modal fade" role="dialog">
<div class="modal-dialog Modal-Wrapper">
<div class="modal-content">
<div class="modal-header Modal-Header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Upload New Document</h3>
</div>
<div class="modal-body Modal-Body">
<table>
<tr>
<th>Document :</th>
<td>
<input type="file" id="FileUpload_Modal_Document" />
</td>
</tr>
<tr>
<th>Note :</th>
<td>
<textarea id="TextArea_Modal_Document_Note" style="width: 400px;"></textarea>
</td>
</tr>
</table>
</div>
<div class="modal-footer Modal-Footer">
<button type="button" class="btn btn-success" onclick="enterDocumentInfo()">Upload</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
This is the most important part. I prefer to upload using the $.Ajax such as the example below. I was able to get only the file upload to work with the submitDocument()
Javascript :
function submitDocument()
{
var fileUpload = $("#FileUpload_Modal_Document").get(0);
var files = fileUpload.files;
var data = new FormData();
for (var i = 0; i < files.length; i++) {
data.append(files[i].name, files[i]);
}
var options = {};
options.url = "FileUploadHandler.ashx";
options.type = "POST";
options.data = data;
options.contentType = false;
options.processData = false;
options.success = function (result) { alert("Gud"); };
options.error = function (err) { alert(err.statusText); };
$.ajax(options);
}
$.ajax({
type: "POST",
url: "Lease_View.aspx/enterDocument",
data: JSON.stringify({
leaseID: leaseID,
userID: userID,
note: note
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function ()
{
// Gud
},
error: function ()
{
// Bad
}
});
Codebehind FileUpload
public class FileUploadHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
// Upload code here
}
}
context.Response.ContentType = "text/plain";
context.Response.Write("File(s) Uploaded Successfully!");
}
public bool IsReusable
{
get
{
return false;
}
}
}
WebMethod Codebehind
I prefer to be able to upload file through this instead of above.
[System.Web.Services.WebMethod]
public static void enterDocument(string leaseID, string userID, string note)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
SqlCommand cmd;
cmd = new SqlCommand("INSERT INTO Lease_Documents " +
"(File_Name) " +
"VALUES " +
"(#File_Name)", conn);
cmd.Parameters.AddWithValue("#File_Name", note);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}

I figured it out. Basically how to pass additional parameters is using data.append(name, value) in the javascript. You can receive the value in the .ashx handler by using (HttpContext)context.Request.Form["name"]. Unfortunately it is using the handler instead of the webmethod, but at least it works.
In Javascript
var data = new FormData();
for (var i = 0; i < files.length; i++) {
data.append(files[i].name, files[i]);
}
data.append("Note", note);
In Codebehind
string note = context.Request.Form["Note"].ToString();

Related

Refresh and Clear button aren't working on asp.net application

My 'Clear' and 'Refresh' buttons do not clear out my Branch and Terminal inputs on my webpage. I think it has something to do with my KnockoutJS since I bind the data to a table in the DB. Perhaps the KnockoutJS thing isn't functioning properly. The page is supposed to display the fetched data from the DB everytime 'Refresh' button is clicked too. But it seems like the code doesn't even fetch anything from the DB.
I'm new to learning the framework of asp.net so can anyone pls help me w my issue? T
I tried to look at other API functions and only tweaked a little parameters to fetch from the DB since there are different tables I need to fetch from. I also modified the Stored Procedure of the respective page for the API function to grab the data from SQL Server but still the page appears blank and the buttons aren't working.
buttons html
<div class="col-sm-5 col-md-5 col-lg-5 m-b-15">
<button id="btnRefreshForecastDetails" type="button" class="btn btn-primary btn-custom w-md waves-effect waves-light" data-bind="click: refresh"><i class="mdi mdi-refresh"></i> <span>Refresh</span></button>
<button id="btnClearAll" type="button" class="btn btn-primary btn-custom w-md waves-effect waves-light" onclick="ClearAll();"><i class="mdi mdi-close"></i> <span>Clear All</span></button>
</div>
.JS function
var ObservableModelMain = function () {
var self = this;
self.gifts = ko.observableArray();
self.refresh = function () {
StartLoadingPage();
url = sessionStorage.getItem('WebApiURL') + "IT_GetDetails?ID=" + sessionStorage.getItem('ID');
var table = $('#main-table');//table from DB
var PageSize = sessionStorage.getItem('PageSize');
var valueToPush = {};
var FinalData = [];
valueToPush.PageNumber = table.getPageNum();
valueToPush.PageSize = PageSize;
valueToPush.SortExpression = table.getSortExpression();
valueToPush.SortOrder = table.getSortOrder();
valueToPush.SearchBranchNo = _strSearchBranchNo;
valueToPush.SearchTerminalNo = _strSearchTerminalNo;
valueToPush.SearchDate = _strSearchDate;
FinalData.push(valueToPush);
valueToPush = {};
var myJSON = JSON.stringify(FinalData)
$.ajax({
url: url,
type: "POST",
data: myJSON,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
DeviceStatus = data["errorCode"];
Param = data["param"];
if (DeviceStatus == 'SUCCESS') {
var obj = JSON.parse(Param);
if (obj[0].length == 0 && obj[1][0].TotalOutput != 0) {
document.getElementById('btnRefreshForecastDetails').click();
}
else {
self.gifts(obj[0]);
}
table.updateTable(parseInt(PageSize), obj[1][0].TotalOutput);
//GetBranchList();
}
else {
swal("Error", "Fail to retrieve forecast details, " + Param, "error");
}
CloseLoadingPage();
}
});
}
};
API function
public async Task<TCR_RESPONSEMESSAGE> IT_GetForecastDetails(ITForecast[] Alldata)
{
StringBuilder sbReturnMessage = new StringBuilder();
StringBuilder sbTraceMessage = new StringBuilder();
API_COMPLETEMESSAGE tcm = null;
WebAPITraceLog wtl = null;
string reqStr = string.Empty;
string repStr = string.Empty;
string MessageSeqNo = string.Empty;
const string functionNameStr = nameof(IT_GetForecastDetails);
API_FUNCTION APIFunctionCode = API_FUNCTION.IT_GetForecastDetails;
StringBuilder sbSQLStmt = new StringBuilder();
bool asyncResult = false;
DataSet dsData = new DataSet();
bool blnResult = false;
string strTable = "tblForecastDetails";
List<SqlParameter> SqlParameters = new List<SqlParameter>();
try
{
using (SqlConnection SQLDBConn = new SqlConnection(sqlTCRSecureBODBConnStr))
{
await SQLDBConn.OpenAsync();
SqlParameters.Add(new SqlParameter("#PageNumber", Alldata[0].PageNumber));
SqlParameters.Add(new SqlParameter("#PageSize", Alldata[0].PageSize));
SqlParameters.Add(new SqlParameter("#SortExpression", Alldata[0].SortExpression));
SqlParameters.Add(new SqlParameter("#SortOrder", Alldata[0].SortOrder));
SqlParameter OutputParam = new SqlParameter("#TotalRecords", SqlDbType.BigInt);
OutputParam.Direction = ParameterDirection.Output;
SqlParameters.Add(OutputParam);
blnResult = ReadDataSetByStoredProcedure("GetForecastDetailsWithPage", SqlParameters, strTable, DEFAULT_LOG_NAME, SQLDBConn, ref dsData);
if (blnResult == false)
{
tcm = FAIL_READ_MESSAGE;
tcm.Param = "Fail to read GetForecastDetailsWithPage.";
goto ExitHandler;
}
DataTable tbl = new DataTable("tblPagerInfo");
tbl.Columns.Add("TotalOutput", typeof(long));
tbl.Rows.Add(Convert.ToInt64(SqlParameters[4].Value));
dsData.Tables.Add(tbl);
}
if (dsData != null)
{
tcm = SUCCESS_MESSAGE;
tcm.Param = JsonConvert.SerializeObject(dsData.Tables);
goto ExitHandler;
}
else
{
tcm = FAIL_READ_MESSAGE;
tcm.Param = "Fail to read GetForecastDetailsWithPage.";
goto ExitHandler;
}
ExitHandler:
tcm.Function = APIFunctionCode;
return await ProcessAPICompleteMessage(tcm, functionNameStr);
}
catch (Exception ex)
{
string errorMessages = string.Empty;
errorMessages += "Description : " + ex.Message;
LogError(DEFAULT_LOG_PATH, DEFAULT_LOG_NAME, errorMessages, GetLineNumber(ex).ToString(), functionNameStr);
tcm = EXCEPTION_MESSAGE;
tcm.Function = APIFunctionCode;
tcm.Param = errorMessages;
return await ProcessAPICompleteMessage(tcm, functionNameStr);
}
}
I expect for the "Refresh" and "Clear" buttons to work, and for the DB data from the declared table to be fetched to be displayed on the web page.
well, for starters I don't see your knockout anywhere being bound to your viewmodel, preferably below your viewmodel definition.
ko.applyBindings(new ObservableModelMain());
and secondly your clear button has a plain old javascript onclick event attribute, not a data-bind to a -also not available- self.clear = function() {...} in your knockout viewmodel

why does my postback in Chrome not refresh my page

I have a postback that should refresh my page and reload page. When the page reloads it should display an image or an uploaded link or an uploaded document link or something. This works great when I run locally, but when I have deployed the same code to my host server, the page reloads with blanks, and the user must hit refresh to see the results. the following code snippet asks the user to upload an image, and then performs an update:
markup:
<form id="updateLogo" enctype="multipart/form-data">
<div class="container">
<div class="row">
<div class="col-lg-6 col-md-12">
<h5 class="red"><b>(Image sizes are limited to 1 Megabyte)</b></h5>
Select File:
<input class="form-control" type="file" name="file" id="file" required="required" />
<input class="form-control" type="hidden" name="communityId" id="communityId" value="#ViewBag.CommunityId" />
</div>
<div class="col-lg-6 col-md-12">
Current Profile Image:
<img src="#ViewBag.LogoImage" class="img-responsive img-circle" style="width:150px; height:150px" />
</div>
</div>
<div class="row">
<div class="col-lg-6 col-md-12">
<input type="submit" value="Upload Image" class="btn btn-habitat" id="updtLogo">
</div>
</div>
</div>
</form>
javascript with ajax :
$("#updtLogo").click(function () {
// Host
var hostname = location.hostname;
var host = '#System.Configuration.ConfigurationManager.AppSettings["hostroot"]';
if (hostname == "localhost")
host = "";
// New Form data including the newly uploaded file
var formSerialized = $("#updateLogo").serializeArray();
var formdata = new FormData();
var logofile = $("#file")[0].files[0];
// Supporting Assets (i.e. uploaded files go here)
for (i = 0; i < $("#file")[0].files.length; i++) {
formdata.append("File", $("#file")[0].files[i]);
}
$.each(formSerialized, function (i, field) {
formdata.append(field.name, field.value);
});
var communityId = $("#communityId").val();
var fileLogo = $("#file").val();
// Only allow if file size is less than 1MB
if (logofile.size < (1024 * 1024)) {
$.ajax({
type: "POST",
url: host + "/Communities/UploadLogo/" + communityId + "?logo=" + fileLogo,
contentType: false,
processData: false,
data: formdata,
success: function () {
console.log('success!!');
}
});
window.location.reload();
} else {
var errorMsg = 3;
$(".modal-dialog").css({
"left": 0,
"top": 200,
});
$(".modal-body").css({
"background-color": "green"
})
$(".modal-title").text("Error Uploading Logo Image");
var url = host + "/Communities/ErrorMessageDialog/" + communityId + "?errorMsg=" + errorMsg;
$("#inviteDialog").load(url, function () {
$("#inviteModal").modal("show");
})
}
return false;
});
MVC ActionResult
[HttpPost]
[Authorize]
public ActionResult UploadLogo(int id, string logo)
{
// Uploaded data files go here
HttpPostedFileBase file = Request.Files[0];
var logoFile = file.FileName != null ? file.FileName : logo;
if (logoFile != null || logoFile != "")
{
var fileName = Path.GetFileName(logoFile);
var host = ConfigurationManager.AppSettings["hostroot"];
if (System.Web.HttpContext.Current.Request.IsLocal)
host = "";
var communityId = id;
// var fileName = file.FileName;
var directory = Server.MapPath("~/CommunityStorage/" + communityId + "/Logo/");
var virtualPath = host + "/CommunityStorage/" + communityId + "/Logo/";
// Create a new directory for the community if it does not exist based on their community id
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
var path = Path.Combine(directory, fileName);
file.SaveAs(path);
// Save file path to the Communities Table
var community = db.Communities.Where(x => x.CommunityId == communityId).SingleOrDefault();
if (community == null)
return RedirectToAction("Index", "login");
// Update the Logo in the communities table
community.LogoPath = virtualPath + fileName;
db.SaveChanges();
}
return View();
}
From the comments:
the typical pattern for ajax follows as:
$.ajax({ ... success: function(data) { /* Do stuff here */ } });
If you are looking to reload the page after you receive your data do so in the callback like so:
$.ajax({
...
success: function(data) {
window.location.reload();
}
});
Be careful when reloading the page: JavaScript data doesn't persist after page reload unless you're using cookies / caching.

MVC Jquery file upload Request.Files is always empty

I have been searching online looking for the answer to this problem but I cannot seem to find anything that works, I have the following Controller code:
[HttpPost]
public ActionResult UploadFiles()
{
// If files exist
if (Request.Files != null && Request.Files.Count > 0)
{
// ** Do stuff
return Json(new { result = true, responseText = "File(s) uploaded successfully" });
}
// Return no files selected
return Json(new { result = false, responseText = "No files selected" });
}
And following code in my cshtml page which works fine and the controller can see the files that I upload:
<input type="file" name="files" id="files" accept="image/*;capture=camera" multiple>
<button type="button" onclick="submitform()">Submit</button>
<script>
function submitform(){
// Get files from upload
var files = $("#files").get(0).files;
// Create form data object
var fileData = new FormData();
// Loop over all files and add it to FormData object
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
// Send files to controller
var xhr = new XMLHttpRequest();
xhr.open("POST", "/Quotes/QuoteFiles/UploadFiles", false);
xhr.send(fileData);
}
</script>
However when I try and change this to work using an Ajax call as shown below then Request.Files in the Controller always has no files. The only bit I have changed is the "Send files to controller" part:
<input type="file" name="files" id="files" accept="image/*;capture=camera" multiple>
<button type="button" onclick="submitform()">Submit</button>
<script>
function submitform(){
// Get files from upload
var files = $("#files").get(0).files;
// Create form data object
var fileData = new FormData();
// Loop over all files and add it to FormData object
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
// Send files to controller
$.ajax({
url: '/Quotes/QuoteFiles/UploadFiles',
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: fileData,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
}
</script>
I am running this in Google Chrome but I have tried IE 11 and Edge but not of them work. Can anyone tell me what I am doing wrong?
try using a fileReader instead of a formData and change the mimetype to 'text/plain; charset=x-user-defined-binary'
https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications#Example_Uploading_a_user-selected_file
I have finally found what was causing this issue, I have the following code on my _Layout.cshtml page which is there to automatically send the AntiForgeryToken on any ajax requests I make, this appears to be causing the problem because once I remove it Request.Files is not empty. I now need to see if I can find a way to add this code back in where it will not stop file uploads working:
$(document).ready(function () {
var securityToken = $('[name=__RequestVerificationToken]').val();
$(document).ajaxSend(function (event, request, opt) {
if (opt.hasContent && securityToken) { // handle all verbs with content
var tokenParam = "__RequestVerificationToken=" + encodeURIComponent(securityToken);
opt.data = opt.data ? [opt.data, tokenParam].join("&") : tokenParam;
// ensure Content-Type header is present!
if (opt.contentType !== false || event.contentType) {
request.setRequestHeader("Content-Type", opt.contentType);
}
}
});
});
**** EDIT ****
I have now reworked this as shown below to add 'if(opt.data != "[object FormData]"' which resolves the issue by not calling the code if it is a file upload:
$(document).ready(function () {
var securityToken = $('[name=__RequestVerificationToken]').val();
$(document).ajaxSend(function (event, request, opt) {
if (opt.hasContent && securityToken) { // handle all verbs with content
// If not "FormData" (i.e. not a file upload)
if (opt.data != "[object FormData]")
{
var tokenParam = "__RequestVerificationToken=" + encodeURIComponent(securityToken);
opt.data = opt.data ? [opt.data, tokenParam].join("&") : tokenParam;
// ensure Content-Type header is present!
if (opt.contentType !== false || event.contentType) {
request.setRequestHeader("Content-Type", opt.contentType);
}
}
}
});
});

base64 code send to server by java script, ajax

I am using Html5, Java script, ajax and java. I am uploading a image from desktop to the crop and after the crop it is showing in bootstrap modal in same page. But i am not getting URL for this Image, I am getting some Base64 code and when i am sending this base64 code than it is not working.
I seen this post but i did not get any solution from this link:
https://stackoverflow.com/
This code for static image, Showing first time.
My code:
HTML:
<div class="img-container">
<img src="../assets/img/picture.jpg" alt="Picture">
</div>
<div class="modal fade docs-cropped" id="getCroppedCanvasModal" aria-hidden="true" aria-labelledby="getCroppedCanvasTitle" role="dialog" tabindex="-1">
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<a class="btn btn-primary" id="download" download="cropped.png" href="javascript:void(0);">Upload</a>
</div>
</div>
Java script Code:
(function () {
var $image = $('.img-container > img');
var $download = $('#download');
$('#getCroppedCanvasModal').modal().find('.modal-body').html(result);
if (!$download.hasClass('disabled')) {
$download.attr('href', result.toDataURL());
//console.log("*****************"+result.toDataURL());
var swapUrl = result.toDataURL();
console.log("*******" + swapUrl);
// document.getElementById('replaceMe').src = swapUrl;
$('#download').click(function () {
var b = result.toDataURL();
$.ajax({
url: "/sf/p/customizeText",
type: 'GET',
data: b,
success: function (response) {
console.log("999999999999999999999999999999999----------------" + b)
},
complete: function (response) {
},
error: function (response) {
}
});
});
}
}
I am assign result.toDataURL() into variable b. But it is showing some base64 code.
How i am send this image to server.
I am giving one snippet.
Please give me some idea achieve to this solution.
Hi you can check this solution also
Javascript code
var base64before = document.querySelector('img').src;
var base64 = base64before.replace(/^data:image\/(png|jpg);base64,/, "");
var httpPost = new XMLHttpRequest();
var path = "your url";
var data = JSON.stringify(base64);
httpPost.open("POST", path, false);
// Set the content type of the request to json since that's what's being sent
httpPost.setRequestHeader('Content-Type', 'application/json');
httpPost.send(data);
This is my Java code.
public void saveImage(InputStream imageStream){
InputStream inStream = imageStream;
try {
String dataString = convertStreamToString(inStream);
byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(dataString);
BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes));
// write the image to a file
File outputfile = new File("/Users/paul/Desktop/testkey/myImage.png");
ImageIO.write(image, "png", outputfile);
}catch(Exception e) {
System.out.println(e.getStackTrace());
}
}
static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}

AJAX Show Image after Upload

i working on uploading files using ajax for almost 3 hours and successfully managed to make it work, please check the code:
View
<div class="form-horizontal">
<div class="form-group">
#Html.Label("Choose Image(s)", new { #class = "control-label col-sm-3" })
<div class="col-sm-5">
<input type="file" name="UploadFile" id="UploadFile" accept=".png, .jpg, .gif" multiple />
</div>
</div>
<div class="form-group">
<div class="col-sm-5 col-sm-offset-3">
<input type="button" value="Save" id="save" class="add btn btn-primary" />
<div style="color:red">
#ViewBag.error
</div>
</div>
</div>
</div>
<div style="margin-top: 17px;">
#foreach (var item in Model.Content)
{
<div class="gallery">
<a href="#item.ImagePath" title="#item.Description" data-gallery>
<img src="#item.ThumbPath" alt="#item.Description" class="img-rounded" style="margin-bottom:7px;" />
</a>
<input type="button" class="delete btn btn-danger" value="Delete" data-picid="#item.PhotoId" />
</div>
}
</div>
Controller
[HttpPost]
public ActionResult Create(Photo photo)
{
var model = new Photo();
foreach (string file in Request.Files)
{
var fileContent = Request.Files[file];
if (fileContent.ContentLength == 0) continue;
model.Description = photo.Description;
var fileName = Guid.NewGuid().ToString();
var extension = System.IO.Path.GetExtension(fileContent.FileName).ToLower();
using (var img = System.Drawing.Image.FromStream(fileContent.InputStream))
{
model.ThumbPath = String.Format(#"/GalleryImages/thumbs/{0}{1}", fileName, extension);
model.ImagePath = String.Format(#"/GalleryImages/{0}{1}", fileName, extension);
// Save thumbnail size image, 100 x 100
SaveToFolder(img, fileName, extension, new Size(200, 200), model.ThumbPath);
// Save large size image, 800 x 800
SaveToFolder(img, fileName, extension, new Size(600, 600), model.ImagePath);
}
// Save record to database
model.CreatedOn = DateTime.Now;
db.Photos.Add(model);
db.SaveChanges();
}
return Json("File Uploaded Successfully");
}
JQuery/AJAX
<script type="text/javascript">
$('#UploadFile').on('change', function (e) {
var $this = $(this);
var files = e.target.files;
if (files.length > 0) {
if (window.FormData !== undefined) {
var data = new FormData();
for (var x = 0; x < files.length; x++) {
data.append("file" + x, files[x]);
}
$.ajax({
type: "POST",
url: '/Home/Create',
contentType: false,
processData: false,
data: data,
success: function (result) {
console.log(result);
//add code to refresh the gallery with the new uploaded image
},
error: function (xhr, status, p3, p4) {
var err = "Error " + " " + status + " " + p3 + " p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
console.log(err);
}
});
} else {
alert("Error! This browser does not support file upload, please change your browser");
}
}
});
</script>
SavetoFolder
private void SaveToFolder(Image img, string fileName, string extension, Size newSize, string pathToSave)
{
// Get new image resolution
Size imgSize = NewImageSize(img.Size, newSize);
using (System.Drawing.Image newImg = new Bitmap(img, imgSize.Width, imgSize.Height))
{
newImg.Save(Server.MapPath(pathToSave), img.RawFormat);
}
}
NewImageSize
public Size NewImageSize(Size imageSize, Size newSize)
{
Size finalSize;
double tempval;
if (imageSize.Height > newSize.Height || imageSize.Width > newSize.Width)
{
if (imageSize.Height > imageSize.Width)
tempval = newSize.Height / (imageSize.Height * 1.0);
else
tempval = newSize.Width / (imageSize.Width * 1.0);
finalSize = new Size((int)(tempval * imageSize.Width), (int)(tempval * imageSize.Height));
}
else
finalSize = imageSize; // image is already small size
return finalSize;
}
but the problem is i have to refresh the browser to see the added image, what should i put in ajax on sucess upload to add the image dynamically without refreshing browser?
Since you are having option to upload multiple images I would suggest to go with below approach:
your controller now would look like:
[HttpPost]
public ActionResult Create(Photo photo)
{
List<Photo> model = new List<Photo>();
//create list of photo model
foreach (string file in Request.Files)
{
var fileContent = Request.Files[file];
if (fileContent.ContentLength == 0) continue;
var fileName = Guid.NewGuid().ToString();
var extension = System.IO.Path.GetExtension(fileContent.FileName).ToLower();
string thumpath,imagepath = "";
using (var img = System.Drawing.Image.FromStream(fileContent.InputStream))
{
model.Add(new Photo(){
Description=photo.Description,
ThumbPath = String.Format(#"/GalleryImages/thumbs/{0}{1}", fileName, extension),
ImagePath = String.Format(#"/GalleryImages/{0}{1}", fileName, extension),
CreatedOn=DateTime.Now
});
//fill each detail of model here
thumpath = String.Format(#"/GalleryImages/thumbs/{0}{1}", fileName, extension);
//separate variables to send it to SaveToFolder Method
imagepath = String.Format(#"/GalleryImages/{0}{1}", fileName, extension);
SaveToFolder(img, fileName, extension, new Size(200, 200), thumpath);
SaveToFolder(img, fileName, extension, new Size(600, 600), imagepath);
}
}
foreach(var md in model)
{
//loop again for each content in model
db.Photos.Add(md);
db.SaveChanges();
}
return Json(new {model=model },JsonRequestBehavior.AllowGet);
//return the model here
}
in ajax success you can create the image with the model returned values as below:
success: function (result) {
var model = result.model;
$(model).each(function (key,value) {
$('<img />').attr({
src: value.ThumbPath
}).appendTo("body");
//note you can append it to anywhere, like inside container or something
})
}
I would set the src attribute of the img tag usign jQuery in your success function:
success: function (result) {
$("img").attr('src' , '/path/to/your/img');
},
If you don't know the public path to your image on client side you can use the response object:
return Json("{ path : "+model.ImagePath+"."+fileName+"."+extension+"}");
There is a few possibilities, which to use depends on pictures size etc.
Personaly I (if images are not too big) would on server side convert image ot base64 and return it with ajax and display the data returned from server, of course it would need conversion as well.
Check out this article, i think i'll help you :)
Base64 encoded image

Categories