I am having an unusual issue when I deploy my code from VS2015 to IIS. In VS when I run the web code, either as debug or release, the image I select and load then convert to base64 is converted to a byte array and saved to the database without any problems. However, when I deploy to the web server the code fails to work and the image is never updated. I am not getting any error information. As long as I run it from VS it all works. Is there something on the IIS server that needs to be configured? Any help or comments will be greatly appreciated.
HTML CODE
<form class="input-group" id="img2b64">
<input id="inputFileToLoad" name="files" type="file"
onchange="encodeImageFileAsURL();" />
</form>
<!-- is used to display b64 code and hold the b64 for ajax call to controller -->
<textarea id="b64" class="form-control"></textarea>
JQUERY CODE
function encodeImageFileAsURL(cb) {
return function () {
var file = this.files[0];
var reader = new FileReader();
reader.onloadend = function () {
cb(reader.result);
}
reader.readAsDataURL(file);
}
}
$('#inputFileToLoad').change(encodeImageFileAsURL(function (base64Img) {
$('#act_Photo').attr('src', base64Img);
$('#b64').val(base64Img);
}));
IN THE CONTROLLER CODE
// model.ImageFile is the base64 string
if (!string.IsNullOrEmpty(model.ImageFile))
{
// strip out base64 header
int pos = model.ImageFile.LastIndexOf(',') + 1;
string data = model.ImageFile.Substring(pos);
// get byte array of base64 image
byte[] bytes = Convert.FromBase64String(data);
// convert and save as byte array to DB
var acctImg = new WebImage(bytes).Resize(220, 200, false, true);
// aRec.Photo is in DB record
aRec.Photo = acctImg.GetBytes();
}
Seems like all is well. I restarted the site in IIS. Seems to have been a caching issue causing all the grief. Sometimes I just hate caching.
Related
I'm doing a file upload function in my ASP.NET MVC web system. The file upload function is working, so the next step I do is to validate the file size.
Please see the attached codes
Partial form GEDocumentInfoForm.ascx:
<input type="file" name = "Files" class = "multi" id = "myFile"/>
Main Form Create.aspx
<asp:Content ID="Content4" ContentPlaceHolderID="ContentCph" runat="server">
<script type="text/javascript">
$(document).on('click', '#btnCreateDocument', function () {
$('#btnCreateDocument').attr('disabled', 'disabled'); // prevent resubmit
Checksize()
document.body.style.cursor = 'wait';
});
function Checksize() {
alert(document.getElementById("myFile").tagName);
var k = document.getElementById("myFile").files[0].size;
alert("file size in KB " + k / 1024);
}
</script>
<% Using (Html.BeginForm("Create", "GEDocument", FormMethod.Post, New With {.enctype = "multipart/form-data", .id = "form"}))%>
<input type="submit" name="Save" value="<%= Detail.Save %>" id="btnCreateDocument" />
<div id="Div1">
<% Html.RenderPartial("GEDocumentInfoForm", Model) %>
</div>
<% End Using%>
</asp:Content>
The file size validation (not more than 2048B) was working fine in localhost. So, after that I published it and deploy in my development server. When I run it, somehow it can pass through my validation. After check in debug mode of web browser, it returns 0 for the file size.
var k = document.getElementById("myFile").files[0].size;
I've tried to search solutions to see if anyone hit the similar issue before. End up, I have to use server validation in my Controller.
Dim fileZs As HttpFileCollectionBase = Request.Files
For z As Integer = 0 To (fileZs.Count - 1)
Dim file As HttpPostedFileBase = fileZs(z)
If Not IsNothing(file) AndAlso (file.ContentLength / 1024) > 2048 Then
errors.Concat(New RuleViolation(Message.EmailMustHaveValue, "SelectedToEmails"))
End If
Next
Web.Config (added the configuration so that it can pass ActionFilterAttribute in Controller due to Maximum request too long)
<system.web>
<httpRuntime maxRequestLength="1048576" />
</system.web>
I think that server validation is not user-friendly. I wish there are some answers from the experts if anyone faced the issue like me in doing Client validation to check file size in file upload feature.
Why is it always return 0 after published to development server?
Is it related to server security? As I know we are getting FileName as C:\fakePath\myFileName. Could it be some relationship over here?
here a full working example, note Request.Files is an array, if you are sending only one file you need to pick first item.
the right property to check is ContentLength
also check if in your folder the uploaded file exists after upload, because you need to have write permission in the folder where you are uploading
[HttpPost]
public ActionResult Upload()
{
if (Request.Files.Count > 0)
{
var file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
file.SaveAs(path);
}
}
//............
}
I am using a generic handler to download csv/excel files. It was working fine until yesterday. Today suddenly it stopped working on deployment on IIS 7.5 (though he same code works well in visual studio debugging mode). Here is my code:
ASPX: This is a content page
<input type="button" class="btn-primary" id="btnDownload" title="Download" value="Download" onclick='return downloadReport(this);' data-toggle="modal" data-target="#myModal" navurl='<%: ResolveUrl("~/Handlers/DownloadData.ashx") %>' />
JS:
function downloadReport(btn) {
//I am using a kendoUI combo box and kendo js + also using bootstrap for design & modal popups & also i have applied bundling to kendo & bootstrap files. They seem to be working fine without any conflicts as all their api's are working.
var $mod = $("#masterModal");
$mod.modal('show');
//window.location = "Handlers/DownloadData.ashx?rtp=" + combobox.val();
window.location.href = $(btn).attr("navurl") + "?rtp=" + combobox.val();
setTimeout(function () {
$mod.modal("hide");
}, 2000);
return false;
}
Master Page:
I am including the js file containing the above method just before end of body tag.
<script src='<%: ResolveUrl("~/Scripts/DataUploader.js") %>'></script>
</body>
</html>
Handler: In handler Process Request Method
HttpResponse response = this._context.Response;
HRReportData hrData = new HRReportData(ConfigMaster.DbProvider, ConfigMaster.ConnectionString, ConfigMaster.DBSchemaName);
ReportDataManager rdm = null;
ExcelPackage xlPackage = null;
try
{
rdm = new ReportDataManager();
DataSet ds = rdm.GetReportData(hrData, report_Type);
if (ds != null && ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
xlPackage = new ExcelPackage();
ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets.Add(report_Type.ToString());
worksheet.Cells["A1"].LoadFromDataTable(ds.Tables[0], true, TableStyles.Light1);
response.ClearHeaders();
response.ClearContent();
response.Clear();
response.ContentType = "application/octet-stream";
response.AppendHeader("content-disposition", "attachment; filename=" + report_Type.ToString() + ".xlsx");
xlPackage.SaveAs(response.OutputStream);
response.Flush();
//response.Close();
//response.End();
}
}
}
catch (Exception ex)
{
//LogError.MethodLevelError(Convert.ToString(Session["Username"]), ex);
if (!(ex is System.Threading.ThreadAbortException))
{
//Other error handling code here
}
}
finally
{
if (xlPackage != null)
{
xlPackage.Dispose();
xlPackage.Dispose();
}
}
Bundle config:
bundles.Add(new ScriptBundle("~/Kendo/kendo").Include(
"~/Scripts/jquery-1.11.3.min.js",
"~/Kendo/js/kendo.all.min.js"
// "~/Scripts/DataUploader.js"
));
bundles.Add(new ScriptBundle("~/bootstrap/bootstrap").Include(
"~/bootstrap/js/holder.js",
"~/bootstrap/js/ie10-viewport-bug-workaround.js",
"~/bootstrap/js/ie-emulation-modes-warning.js",
"~/bootstrap/js/bootstrap.min.js"
));
All above code works well in debugging mode and was working well in deployment mode as well. Don't know what has changed that it suddenly stopped working and I am unable to find out any reasons :(
Behaviour on deployment: Instead of staying on same page and downloading file it navigates to Handler and a blank screen is displayed. No file is downloaded.
Behaviour in debuuging mode OR when run using vs2012 express: It stays on same page and downloads the file as expected.
Somebody please help me on this.
All the above code works 100% fine. There is absolutely no mistake in it. I found the reason that it was not working was that the web.config in the published folder was not updated/overwritten by someone and since the work is in beginning phase I have not yet added support for Exception handling/error logging hence the handler error (due to accessing keys used in config files) were not noted & in debug/dev environment the config file was correct hence the error never occurred.
Anyways the code can be useful to anyone who wish to download the files using generic handler. However kindly note that above code is in basic stage and needs to be updated for:
1) user request validation -parameter validation
2) user session validation
3) security implementations
4) exception handling
5) logging
I've developed a simple flex app with embedded swf. Basically swf use Loadvars to get data from particular database table. Ok, when I tested the flex app on localhost it is works fine and embedded swf make its sendAndLoad calls correctly.
But! When it is located on the web server swf not work correctly. I meant there is not returned values by sendAndLoad method.
Well, to make some points: questionContentLoadVars.img1 holds(return) the string from php call. This "img1" is an empty returned string only in Flex app placed in the web server otherwise it returns correct value from php call?
When gameplay22.swf is standallone works!
When gameplay22.swf is in HTML page works!
When gameplay22.swf is embedded in FLex and executed in LOCALHOST works!
But in the web server this embedded gameplay22.swf doesn`t works!
What is the problem with it?
//* here is flash(swf) part of gameplay22.swf file which is embedded in the Flex by SWFLOader(gameplay22.swf)
questionContentLoadVars = new LoadVars();
questionContentLoadVars.onLoad = function(success){
if (success){
slidingSvityk_mc.descripTA_mc.description_ta.text = questionContentLoadVars.theContent;
}
else
{
slidingSvityk_mc.description_ta.text = "err!";
}
};
function loadQuestionData(sectionID){
var tablename ='questionsgeo'; // database tablename
//sending variables to the PHP script
questionContentLoadVars.row = sectionID;
questionContentLoadVars.tablename = tablename;
questionContentLoadVars.id_ = "";
questionContentLoadVars.img1 = "";
questionContentLoadVars.sendAndLoad("getQuestionRec.php",questionContentLoadVars,"_POST");
};
function showLoadedGalleryImages():Void{
infphp.text = questionContentLoadVars.img1;
var img1Bulk:MovieClip = new MovieClip();
img1Bulk = imgGalleryContainer_mc.img1Bulck_mc.createEmptyMovieClip(img1Bulk, _root.getNextHighestDepth());
img1Bulk._x = 0;
img1Bulk._y = 0;
image_mcl.loadClip(questionContentLoadVars.img1, img1Bulk);
};
//* And here is Flex part of embedded SWFLOader(gameplay22.swf) component
<s:SWFLoader includeIn="user" width="1024" height="768" horizontalCenter="0" source="gameplay22.swf" verticalCenter="0"/>
I mean, when a user chooses the video file from their system, have the web-page already show them the files they want to upload.
I'm already using image file to preview using FileAPI JS. The same I want to do with FileAPI JS for video file.
(So, It must be work within my client side)
Thanks & answers are appreciated :)
You can either use FileReader or createObjectURL. They'll both get the job done, but FileReader has slightly broader support in browsers.
createObjectURL will run synchronously and return a Blob URL, a short string referencing the file in memory. and you can free it up immediately after you're done using it.
FileReader will run asynchronously, requiring a callback, providing a Data URI, a much longer string representing the whole file. This can be very big and will be freed from memory in Javascript garbage collection.
Here's an example that first tries createObjectURL and falls back to FileReader. (Please provide your own error checking, etc.)
var video = document.getElementById('video'),
input = document.getElementById('input');
input.addEventListener('change', function (evt) {
var reader = new window.FileReader(),
file = evt.target.files[0],
url;
reader = window.URL || window.webKitURL;
if (reader && reader.createObjectURL) {
url = reader.createObjectURL(file);
video.src = url;
reader.revokeObjectURL(url); //free up memory
return;
}
if (!window.FileReader) {
console.log('Sorry, not so much');
return;
}
reader = new window.FileReader();
reader.onload = function(evt) {
video.src = evt.target.result;
};
reader.readAsDataURL(file);
}, false);
Working example here: http://jsbin.com/isodes/1/edit
Mozilla has a more detailed article with instructions on how to upload once you've got your file.
IE10 supports both, but IE9 supports neither, so you'll have to fall back to a regular form upload without a preview.
I need to upload a file to my server. I have no prior knowledge to server side programming and need some advice I can understand. I have my file (JPEG Image) in a byte array in my Windows Phone app. I now need to upload it to my server. I currently have a sample that uses HttpWebRequest with post, but I do not know how to handle the data in that post from the asp page. If you could explain how to do this it would be great, but I am open to any alternatives, providing they can be used with Windows Server.
The code I am currently using: ('b' is the byte array for the file)
var uri = "http://www.masonbogert.info/mcode/default.aspx";
var request = HttpWebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "image/jpeg"; // Change to whatever you're uploading.
request.BeginGetRequestStream((result1) =>
{
using (Stream stream = request.EndGetRequestStream(result1))
{
stream.Write(b, 0, b.Length);
}
request.BeginGetResponse((result2) =>
{
var response = request.EndGetResponse(result2);
// Optionally handle the response.
var responseStream = response.GetResponseStream();
Dispatcher.BeginInvoke(new readstreamdelegate(readstream), responseStream);
}, null);
}, null);
Remember, when it comes to ASP and any other server side programming I have no prior knowledge, so please explain!
You can try to use the "WebClient" class for getting it. More information you can get there: "http://msdn.microsoft.com/en-us/library/system.net.webclient(v=vs.80).aspx".
Please see this page: http://nediml.wordpress.com/2012/05/10/uploading-files-to-remote-server-with-multiple-parameters/#more-234