Internal Server Error in JavaScript ajax with asp.net - javascript

I'm still a beginner in JavaScript and ajax. I have this problem in my code where I try to upload an image from an ajaxfileupload but the error for JavaScript will always popup, saying that it has an internal server error. What possible mistakes I made in my code?
Here is the aspx code:
<%# Page Language="C#" AutoEventWireup="true"
CodeFile="CreateBrands.aspx.cs" Inherits="Pages_CreateBrands" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit"
TagPrefix="asp"%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Music Store</title>
<script src="../Javascript/jquery-1.11.2.min.js"></script>
<script type="text/javascript">
function uploadComplete(sender, args) {
var txt = document.getElementById("validatePicture1");//Your
hiddenfield id
txt.value = "1";
$.ajax({
type: "POST",
url: "CreateBrands.aspx/GetPath1",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
OnSuccess1(result.d);
},
error: function (xhr, status, error) {
OnFailure1(xhr,status,error);
}
});
}
function OnSuccess1(result) {
var pp = document.getElementById("PicturePath1");
pp.value = result;
}
function OnFailure1(xhr,status,error) {
alert("Request: " + xhr + "\n\nStatus: " + status + "\n\nError: " +
error);
}
</script>
<script type="text/javascript">
function uploadComplete2(sender, args) {
var txt = document.getElementById("validatePicture2");//Your
hiddenfield id
txt.value = "1";
$.ajax({
type: "POST",
url: "CreateBrands.aspx/GetPath2",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
OnSuccess1(result.d);
},
error: function (xhr, status, error) {
OnFailure1(xhr,status,error);
}
});
}
function OnSuccess1(result2) {
var pp = document.getElementById("PicturePath2");
pp.value = result;
}
function OnFailure1(xhr,status,error) {
alert("Request: " + xhr + "\n\nStatus: " + status + "\n\nError: " +
error);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div id="wrapper">
<div id="content_area">
<h3> </h3>
<h3 class="headingTitle">Create New Brand(Step 1 of 2):</h3>
<table cellspacing="15" class="brandsTable">
<br/>
<h3 class="headingTitle">Create New Item(Step 2 of 2):</h3>
<table cellspacing="15" class="brandsTable">
<tr>
<td style="width: 160px; height: 37px;">
<strong>Item Type:</strong></td>
<td style="height: 37px">
<asp:RadioButton ID="itemType1" runat="server"
Text="Guitar" AutoPostBack="False" GroupName="itemType"/>
<asp:RadioButton ID="itemType2" runat="server"
Text="Bass" AutoPostBack="False" GroupName="itemType"/>
</td>
</tr>
<tr>
<td style="width: 160px; height: 37px;">
<strong>Item Image1:</strong></td>
<td style="height: 37px">
<br />
<asp:AjaxFileUpload ID="itemFileUpload1"
runat="server" OnUploadComplete="itemUploadImage1_Click"
OnClientUploadComplete="uploadComplete" MaximumNumberOfFiles="1"/>
<asp:HiddenField ID="validatePicture1" Value=""
runat="server" />
</td>
</tr>
<tr>
<td style="width: 160px; height: 37px;">
<strong>Item Image2:</strong></td>
<td style="height: 37px">
<br />
<asp:AjaxFileUpload ID="itemFileUpload2"
runat="server" OnUploadComplete="itemUploadImage2_Click"
OnClientUploadComplete="uploadComplete2" MaximumNumberOfFiles="1"/>
<asp:HiddenField ID="validatePicture2" Value=""
runat="server" />
</td>
</tr>
</table>
<asp:Label ID="lblResult2" runat="server" Text="">
</asp:Label>
<br />
<asp:Button ID="Button1" runat="server"
CssClass="submitButton" Text="Save Item" OnClick="Button1_Click"/>
</div>
</div>
</form>
</body>
</html>
And here is the code-behind. By the way, it also has an object reference null in the method GetPath1 with this line of code: string retval = Session["PicturePath1"].ToString();:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit;
public partial class Pages_CreateBrands : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private void ClearTextFields2()
{
itemBrand.Text = "";
itemModel.Text = "";
itemPrice.Text = "";
itemDescription.Text = "";
itemNeckType.Text = "";
itemBody.Text = "";
itemFretboard.Text = "";
itemFret.Text = "";
itemNeckPickup.Text = "";
itemBridgePickup.Text = "";
itemBridge.Text = "";
itemHardwareColor.Text = "";
}
[System.Web.Services.WebMethod]
public string GetPath1()
{
System.Web.SessionState.HttpSessionState Session =
System.Web.HttpContext.Current.Session;
string retval = Session["PicturePath1"].ToString();
Session["PicturePath1"] = null;
return retval;
}
[System.Web.Services.WebMethod]
public string GetPath2()
{
System.Web.SessionState.HttpSessionState Session =
System.Web.HttpContext.Current.Session;
string retval = Session["PicturePath2"].ToString();
Session["PicturePath2"] = null;
return retval;
}
protected void itemUploadImage1_Click(object sender, AjaxFileUploadEventArgs
e)
{
if (itemType1.Checked)
{
string filename = e.FileName;
Session["PicturePath1"] = filename;
itemFileUpload1.SaveAs(Server.MapPath("~/Images/Brands/String
Instrument Items/Guitar/") + filename);
}
else if(itemType2.Checked)
{
string filename = e.FileName;
Session["PicturePath1"] = filename;
itemFileUpload1.SaveAs(Server.MapPath("~/Images/Brands/String
Instrument Items/Bass/") + filename);
}
}
protected void itemUploadImage2_Click(object sender, AjaxFileUploadEventArgs
e)
{
if (itemType1.Checked)
{
string filename = e.FileName;
Session["PicturePath2"] = filename;
itemFileUpload2.SaveAs(Server.MapPath("~/Images/Brands/String
Instrument Items/Guitar/") + filename);
}
else if (itemType2.Checked)
{
string filename = e.FileName;
Session["PicturePath2"] = filename;
itemFileUpload2.SaveAs(Server.MapPath("~/Images/Brands/String
Instrument Items/Bass/") + filename);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (itemType1.Checked)
{
int item_type =
ConnectionClassBrands.GetIdByType(itemType1.Text);
int item_brandId =
ConnectionClassBrands.GetIdByBrand(itemBrand.Text);
string item_model = itemModel.Text;
double item_price = Convert.ToDouble(itemPrice.Text);
string item_image1 = Session["PicturePath1"].ToString();
string item_image2 = Session["PicturePath2"].ToString();
string item_description = itemDescription.Text;
string item_necktype = itemNeckType.Text;
string item_body = itemBody.Text;
string item_fretboard = itemFretboard.Text;
string item_fret = itemFret.Text;
string item_bridge = itemBridge.Text;
string item_neckpickup = itemNeckPickup.Text;
string item_bridgepickup = itemBridgePickup.Text;
string item_hardwarecolor = itemHardwareColor.Text;
ConnectionClassGuitarItems.AddStringInstrumentItems(item_type,
item_brandId, item_model, item_price, item_image1, item_image2,
item_description, item_necktype, item_body, item_fretboard,
item_fret, item_bridge, item_neckpickup,
item_bridgepickup, item_hardwarecolor);
lblResult2.Text = "Upload successful!" + item_image1 + " and " +
item_image2;
}
else if (itemType2.Checked)
{
try
{
int item_type =
ConnectionClassBrands.GetIdByType(itemType2.Text);
int item_brandId =
ConnectionClassBrands.GetIdByBrand(itemBrand.Text);
string item_model = itemModel.Text;
double item_price = Convert.ToDouble(itemPrice.Text);
string item_image1 = Session["PicturePath1"].ToString();
string item_image2 = Session["PicturePath2"].ToString();
string item_description = itemDescription.Text;
string item_necktype = itemNeckType.Text;
string item_body = itemBody.Text;
string item_fretboard = itemFretboard.Text;
string item_fret = itemFret.Text;
string item_bridge = itemBridge.Text;
string item_neckpickup = itemNeckPickup.Text;
string item_bridgepickup = itemBridgePickup.Text;
string item_hardwarecolor = itemHardwareColor.Text;
ConnectionClassGuitarItems.AddStringInstrumentItems(item_type,
item_brandId, item_model, item_price, item_image1, item_image2,
item_description, item_necktype, item_body,
item_fretboard, item_fret, item_bridge, item_neckpickup,
item_bridgepickup, item_hardwarecolor);
lblResult2.Text = "Upload successful!";
ClearTextFields2();
}
catch (Exception ex)
{
lblResult2.Text = ex.Message;
}
}
else
{
Response.Redirect("~/Pages/OverviewGuitarData.aspx");
}
}
}

Related

ASP.NET download PDF feature in UpdatePanel unable to refresh UpdateProgress control

I've two UpdatePanel in a page. The second one has UpdateMode="Conditional" and here there's a link button to produce PDF file.
My goal is to allow the PDF download and in the meantime make a waiting image appear (like an hourglass).
After a few days of studying I reached my goal but i can't hide the image after all operations are terminated.
In the code example i've simplified logic to procude pdf (in complete code i use gridview control data to produce pdf).
If I use an asynchronous PostBackTrigger in UpdatePanel the PDF is not downloaded even if the UpdateProgress (with the expected image) works correctly.
If I use a Synchronous PostBackTrigger in UpdatePanel the PDF is downloaded correctly but the updateProgress does not work because the waiting image remains on the screen. In this case i've used a client side function (postbackButtonClick) to display the image.
I've read many threads but each one is always a little different.
My actual goal is to know if possible on client side when the PDF production operation is complete to hide the image.
Maybe the general approach is wrong?
aspx file
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager runat="server" EnableCdn="true"> </asp:ScriptManager>
<asp:UpdateProgress ID="UpdateProgress1" DynamicLayout="true" runat="server" AssociatedUpdatePanelID="updateGrid" DisplayAfter="0" >
<ProgressTemplate> <div class="progress"> <img src="../images/ajax-loader.gif" /> Waiting...</div> </ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="updateGrid" runat="server">
<ContentTemplate>
<asp:TextBox class='form-control' ID="txtMat" runat="server" style='width:110px' Text="1672"></asp:TextBox>
<asp:Button class='btn btn-primary' ID="cmdGO" runat="server" Text="Execute"/>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel ID="panelCMD" runat="server">
<asp:LinkButton ID="LinkButton3" OnClientClick="return postbackButtonClick();"
runat ="server" CssClass="btn btn-small btn-primary fullwidth" OnClick="mtdCreatePDF"><i class="icon icon-ok"></i> TEST PDF</asp:LinkButton>
</asp:Panel>
</ContentTemplate>
<Triggers >
<asp:PostBackTrigger ControlID="LinkButton3" />
</Triggers>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress2" ClientIDMode="Static" DynamicLayout="true" runat="server" AssociatedUpdatePanelID="UpdatePanel2" DisplayAfter="0" >
<ProgressTemplate>
<div class="progress">
<asp:image id="imgOld" runat="server" imageurl="../images/ajax-loader.gif" />
<br />
<img id="imgLike" src="../images/ajax-loader.gif" /> Attendere...</div>
</ProgressTemplate>
</asp:UpdateProgress>
</div>
</form>
<script src="Test.js" type="text/javascript"></script>
Test.js
function postbackButtonClick() {
updateProgress = $find("UpdateProgress2");
window.setTimeout(function () { updateProgress.set_visible(true); }, 100);
return true;
}
cs file
protected void mtdCreatePDF(object sender, EventArgs e)
{
byte[] content = null;
string TypeOutput = "RESPONSE";
string suffix = #"Pdf_PROD\Print.pdf";
string nameTGT = HttpContext.Current.Server.MapPath("~") + suffix;
var stream = new MemoryStream();
var writer = new PdfWriter(stream);
var pdf = new PdfDocument(writer);
var document = new Document(pdf);
document.Add(new Paragraph("Hello world!"));
document.Close();
if (TypeOutput == "RESPONSE")
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=print.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
//writer.SetCloseStream(false);
Response.BinaryWrite(stream.ToArray());
Response.End();
}
else
{
content = stream.ToArray();
using (FileStream fs = File.Create(nameTGT))
{
fs.Write(content, 0, (int)content.Length);
}
}
}
First, there needs to be a timeoutID for the timeout. We will use it later to disable the timeout. After pdf creation is completed, hideUpdateProgress() function will be called from code-behind to hide the progress image.
Test.js
var timeoutID;
function postbackButtonClick() {
updateProgress = $find("UpdateProgress2");
timeoutID = window.setTimeout(function () { updateProgress.set_visible(true); }, 100);
return true;
function hideUpdateProgress()
{
clearTimeout(timeoutID);
updateProgress = $find("UpdateProgress2");
updateProgress.set_visible(false);
}
To call hideUpdateProgress();, you can add this line at the end of mtdCreatePDF function.
ClientScript.RegisterStartupScript(Page.GetType(),
"hideUpdateProgress",
"hideUpdateProgress();",
true);
I solved it in the following way: I moved everything to the client side.
A. I added a client-side event on the click of the link button
<asp:LinkButton ID="LinkButton6" OnClientClick="return TestPDFDEF();" runat="server" CssClass="btn btn-small btn-primary fullwidth"><i class="icon icon-ok"></i> TEST PDF WebService Def</asp:LinkButton>
B. I added a WebMethod to the page that provides a variable of type [byte] to the Ajax call
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public byte[] GetPDF(List<Classes.GridCosts> MyGrid)
{
foreach (Classes.GridCosts rowsGrid in GrMyGridglia)
{
Console.Write(rowsGrid.Field1);
Console.Write(rowsGrid.Field2);
}
string suffix = #"Pdf_PRODOTTI\Print.pdf";
string nameTGT = HttpContext.Current.Server.MapPath("~") + suffix;
var stream = new MemoryStream();
var writer = new PdfWriter(stream);
var pdf = new PdfDocument(writer);
var document = new Document(pdf);
document.Add(new Paragraph("Hello world!"));
document.Close();
return stream.ToArray();
}
C. I have defined a class for receiving the grid that will be passed to the method
public class GridCosts
{
public string Field1{ get; set; }
public string Field2{ get; set; }
}
D. Added image that appears for hourglass:
$(document).ready(function () {
$('body').append('<div class="progress" id="ajaxBusy"><p><img src="../images/ajax-loader.gif"> Waiting..</p></div>');
$('#ajaxBusy').hide();
//$('#ajaxBusy').css({
// display: "none",
// left: "50%",
// margin: "0px",
// paddingLeft: "0px",
// paddingRight: "0px",
// paddingTop: "0px",
// paddingBottom: "0px",
// position: "fixed",
// right: "3px",
// top: "35%",
// width: "auto"
//});
// Ajax activity indicator bound to ajax start/stop document events
$(document).ajaxStart(function () {
$('#ajaxBusy').show();
}).ajaxStop(function () {
$('#ajaxBusy').hide();
});
});
E. I sent the variable referred to in point B to the user with Javascript
function TestPDFDEF() {
$(function () {
var MyGrid= new Array();
var CostsRow = {};
$('[id*=MyGrid]').find('tr:has(td)').each(function () {
CostsRow.Field1= $.trim($(this).find("td:nth-child(3)").text());
CostsRow.Field2= $.trim($(this).find("td:nth-child(4)").text());
MyGrid.push(CostsRow );
CostsRow = {};
});
type: "POST",
url: "WebService1.asmx/GetPDF",
contentType: "application/json; charset=utf-8",
data: '{MyGrid: ' + JSON.stringify(MyGrid) + '}',
dataType: "json",
beforeSend: function () {
},
success: function (data) {
data = data.d;
var byteArray = new Uint8Array(data);
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob([byteArray], { type: 'application/pdf' }));
a.download = 'FileName';
document.body.appendChild(a)
a.click();
document.body.removeChild(a)
},
complete: function (data) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
});
}

Update panel does not work after calling the function loginByFacebook()

I'm using Facebook Graph JSON responses in my code to deserialize the JSON string.
I created the class as follow.
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div id="fb-root"></div>
Login with Facebook
<br /> <br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
window.fbAsyncInit = function () {
FB.init({ appId: '<%= ecommerce.fblogin.FaceBookAppKey %>',
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true, // parse XFBML
oauth: true // enable OAuth 2.0
});
};
(function () {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
} ());
function loginByFacebook() {
FB.login(function (response) {
if (response.authResponse) {
FacebookLoggedIn(response);
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, { scope: 'email' });
}
function FacebookLoggedIn(response) {
var loc = '/fblogin.aspx';
if (loc.indexOf('?') > -1)
window.location = loc + '&authprv=facebook&access_token=' + response.authResponse.accessToken;
else
window.location = loc + '?authprv=facebook&access_token=' + response.authResponse.accessToken;
}
</script>
</form>
namespace ecommerce
{
public partial class fblogin : System.Web.UI.Page
{
public const string FaceBookAppKey = "xxxxxxxxxx";
protected void Page_Load(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(Request.QueryString["access_token"])) return; //ERROR! No token returned from Facebook!!
//let's send an http-request to facebook using the token
string json = GetFacebookUserJSON(Request.QueryString["access_token"]);
//and Deserialize the JSON response
JavaScriptSerializer js = new JavaScriptSerializer();
FacebookUser oUser = js.Deserialize<FacebookUser>(json);
if (oUser != null)
{
Response.Write("Welcome, " + oUser.name);
Response.Write("<br />id, " + oUser.id);
Response.Write("<br />email, " + oUser.email);
Response.Write("<br />first_name, " + oUser.first_name);
Response.Write("<br />last_name, " + oUser.last_name);
Response.Write("<br />gender, " + oUser.gender);
Response.Write("<br />link, " + oUser.link);
Response.Write("<br />updated_time, " + oUser.updated_time);
Response.Write("<br />birthday, " + oUser.birthday);
Response.Write("<br />locale, " + oUser.locale);
Response.Write("<br />picture, " + oUser.picture);
if (oUser.location != null)
{
Response.Write("<br />locationid, " + oUser.location.id);
Response.Write("<br />location_name, " + oUser.location.name);
}
}
}
private static string GetFacebookUserJSON(string access_token)
{
string url = string.Format("https://graph.facebook.com/me?access_token={0}&fields=email,name,first_name,last_name,link", access_token);
WebClient wc = new WebClient();
Stream data = wc.OpenRead(url);
StreamReader reader = new StreamReader(data);
string s = reader.ReadToEnd();
data.Close();
reader.Close();
return s;
}
public class FacebookUser
{
public long id { get; set; }
public string email { get; set; }
public string name
{ get; set; }
public string first_name
{ get; set; }
public string last_name
{ get; set; }
public string gender
{ get; set; }
public string link
{ get; set; }
public DateTime updated_time
{ get; set; }
public DateTime birthday
{ get; set; }
public string locale
{ get; set; }
public string picture
{ get; set; }
public FacebookLocation location
{ get; set; }
}
public class FacebookLocation
{
public string id
{ get; set; }
public string name
{ get; set; }
}
static int a = 0;
protected void Button1_Click(object sender, EventArgs e)
{
a++;
Label1.Text = Convert.ToString(a);
}
}
}
After added update panel my Facebook login function not working after the link is clicked.
I added AJAX page request manager. The post Back settings function it not work as what I expected.
After I remove added update panel works is working as I expect.
/** This is what I try, but not work */
function loginByFacebook() {
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm != null) {
prm._postBackSettings(function (sender, e) {
if (sender.loginByFacebook.panelsToUpdate != null) {
loginByFacebook();
}
});
};
}
*/
Below is the screenshot issues i'm stuck.
Update panel events are rendered partially hence the events will looses.
After Login or Register Button is click. The Facebook login will not work as expected. The dialog box will not close automatically.

Files are cut off when I upload them to iis7

I want to upload some files to iis 7 by formdata with ajax ,but they are cut into less than 80kb,while it’s alright in debug mode
It can work correctly when the first time I run the IIS, only once.
there is the source code of Up.html, I have removed all the useless function:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="../../js/jquery-1.4.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
function UploadFiles() {
var formData = new FormData();
var files = $('#fileExcel')[0].files;
for (var i = 0; i < files.length; i++) {
formData.append("file[]", files[i]);
}
$.ajax({
url: 'Up.ashx',
type: 'POST',
data: formData,
async: false,
cache:false,
processData: false,
contentType: false,
success: function() {
formData = null;
}
});
}
</script>
</head>
<body>
<form action="Up.ashx" method="post"></form>
<input id="fileExcel" name="file" type="file" multiple="multiple"/>
<button id="btnUpload" onclick="UploadFiles()">上传</button>
</body>
</html>
And there is the code of Up.ashx,I have removed all the useless function:
using System.IO;
using System.Web;
public class Up : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
HttpFileCollection files = context.Request.Files;
if (files.Count<1)
{
context.Response.Write("no file");
context.Response.End();
}
string category = this.GetType().ToString();
string filePath = HttpContext.Current.Server.MapPath("~/FileUpload/" + category + "/");
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
file.SaveAs(filePath+file.FileName);
}
context.Response.Write(files.Count + " files");
context.Response.End();
}
public bool IsReusable {
get {
return false;
}
}
}
When I modified the code like this, it works, I just don't know why.
public Dictionary<string,string> ReceiveFiles(HttpContext context)
{
// return files info as Dictionary
Dictionary<string,string> result = new Dictionary<string, string>();
string category = this.GetType().ToString();
string filePath = HttpContext.Current.Server.MapPath("~/FileUpload/" + category + "/");
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
// the key statement👇,I just don't know why it works
string savePath = context.Request["path"];//"path" can be instead to any keystring,T^T!
string[] files = context.Request.Files.AllKeys;
foreach (string str in files)
{
HttpPostedFile file = context.Request.Files.Get(str);
try
{
file.SaveAs(filePath + file.FileName);
result.Add(file.FileName,filePath+file.FileName);
//context.Response.Write("上传成功!");
}
catch (Exception ex)
{
context.Response.Write("上传失败!错误信息:" + ex.Message.ToString());
return null;
}
}
return result;
}

Trying to add multiple image in a single row

I am trying to insert multiple images in a single row in a field in oracle database, please suggest how to achieve it. Below are the details
image is rendering on the browser and I want to store multiple image through it in oracle db. Each image will have an id generating dynamically
aspx code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html>
<html>
<head>
<style>
input[type="file"] {
display:block;
}
.imageThumb {
max-height: 75px;
border: 2px solid;
margin: 10px 10px 0 0;
padding: 1px;
}
</style>
<title></title>
</head>
<body>
<form id="form1" runat="server">
Find the bellow HTML code
<h2>preview multiple images before upload using jQuery</h2>
<input type="file" id="files" name="files[]" multiple />
<asp:Button ID="Button3" runat="server" BorderColor="#CCFF66"
ForeColor="#0066FF" Text="Insert Data" />
</form>
<script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var a = 0;
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function (e) {
var files = e.target.files,
filesLength = files.length;
if (filesLength == 1) {
a = a + 1;
}
for (var i = 0; i < filesLength ; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function (e) {
var file = e.target;
$("<img></img>", {
class: "imageThumb",
Id: "img"+ a.toString(),
src: e.target.result,
title: file.name
}).insertAfter("#files");
});
fileReader.readAsDataURL(f);
}
});
} else { alert("Your browser doesn't support to File API") }
});
</script>
</body>
</html>
for saving image into oracle db I am using ajax and created webservice to push data into db:
[WebMethod]
public static void SaveUser(User user)
{
String connectionString = ConfigurationManager.ConnectionStrings["conndbprodnew"].ConnectionString;
using (OracleConnection con = new OracleConnection(connectionString))
{
using (OracleCommand cmd = new OracleCommand("INSERT INTO par_cinfo(Product_Id,IMAGETYPE ) VALUES (:IMAGETYPE )", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("IMAGETYPE ", user.IMAGETYPE);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
public class User
{
public decimal Product_Id { get; set; }
public Image IMAGETYPE { get; set; }
}
jQuery ajax on button click to send data to webservices:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
<script type="text/javascript">
$(function () {
$("[id*=Button3]").bind("click", function () {
var user = {};
user.Product_Id = 1;
user.IMAGETYPE= "here dynamic image id which is uploaded should be present "
$.ajax({
type: "POST",
url: "Default.aspx/SaveUser",
data: '{user: ' + JSON.stringify(user) + '}',
//data: JSON.stringify({user:user}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("User has been added successfully.");
window.location.reload();
}
});
return false;
});
});
</script>
The table which I created in oracle is as follows simply for entering the data in the table:
Create table par_cinfo
(
Product_Id NUMBER(10) NOT NULL PRIMARY KEY,
IMAGETYPE BLOB
)

Within javascript function how to modify session variable

I have following code .
In asp.net , I set session variable .Then pass it to javascript for modification .
In javascript I can read session variable value and return modified value in TextBox1 .
In asp.net again , I receive modified session variable value and store it in session variable .
protected void Page_Load(object sender, EventArgs e)
{
Session["MyTest"] = "abcd";
String csname = "OnSubmitScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the OnSubmit statement is already registered.
if (!cs.IsOnSubmitStatementRegistered(cstype, csname))
{
string cstext = " document.getElementById(\"TextBox1\").value = getMyvalSession() ; ";
cs.RegisterOnSubmitStatement(cstype, csname, cstext);
}
if (TextBox1.Text.Equals("")) { }
else {
Session["MyTest"] = TextBox1.Text;
}
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script language=javascript type="text/javascript">
function getMyvalSession() {
var txt = "efgh";
var ff = '<%=Session["MyTest"] %>' + txt;
return ff ;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack=true ></asp:TextBox>
<input type="submit" value="Submit" />
</div>
</form>
</body>
</html>
But my aim was –
Within javascript function itself I should be able to modify session variable .
And I don’t want to use submit button.
Using cookie i can preserve value . Submit button is also not required . So this code has solved my purpose .
<script language="javascript" type="text/javascript">
function writeCookie(name,value,days) {
var date, expires;
if (days) {
date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires=" + date.toGMTString();
}else{
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var i, c, ca, nameEQ = name + "=";
ca = document.cookie.split(';');
for (i = 0; i < ca.length; i++)
{
c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1,c.length);
}
if (c.indexOf(nameEQ) == 0) {
return c.substring(nameEQ.length,c.length);
}
}
return '';
}
function restore(){
var sId = readCookie('sessionId');
document.getElementById("TextBox1").value = sId ;
}
function backup() {
var sId = document.getElementById("TextBox1").value;
writeCookie('sessionId', sId, 3);
}
function getMyvalSession() {
var ff = "Loading Value";
return ff;
}
function TextBox1_TextChanged() {
backup();
}
</script>
<body onload="restore()">
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" Name="TextBox1" runat="server"
AutoPostBack="True" onchange="TextBox1_TextChanged()" ></asp:TextBox>
</div>
</form>
</body>
protected void Page_Load(object sender, EventArgs e)
{
Loading();
}
void Loading (){
String csname = "OnSubmitScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the OnSubmit statement is already registered.
if (!cs.IsOnSubmitStatementRegistered(cstype, csname))
{
string cstext = " document.getElementById(\"TextBox1\").value = getMyvalSession() ; ";
cs.RegisterOnSubmitStatement(cstype, csname, cstext);
}
}
No, session variables cannot be modified on client side directly and expect to change on server. Atleast, AJAX request has to be made to persist the session value.
And based on your current code, I am not understanding significance of session variable. You're just appending text box value with session variable and submitting the form.
So, it would be direct statement without needing client side script, i.e,
//page_load
{
Session["Mytest"] = test;
}
//page_submit
{
Session["Mytest"] += txtName.text;
}
You can define a web method in asp.net or action in MVC and set session inside it from parameter passed
[HttpPost]
public bool SetSessionAction(string param)
{
Session[sessionName] = param;
return true;
}
then call method or action using $.ajax or $.post from jquery.
var paramValue = 'some data';
var targetUrl = "#Url.Action("SetSessionAction", "ControllerName" )";
$.ajax({
type: "POST",
cache: false,
dataType: "json",
url: targetUrl,
data: { param: paramValue },
success: function (s) {
alert('Set Session is: ' + s);
}
});
Good Luck

Categories

Resources