Hi my function is where i need to upload a xml file and check in the folder the file exist or not.
If the file exist i need to replace the file with a pop up in javascript by using ok or cancel and then from the button click i need to save the xml file and bind in a grid. Now im able to save the file but im not able to bind into the grid. Thanks.
My File upload code
if (FileUpload1.HasFile){
if (FileUpload1.PostedFile.ContentType == "text/xml")
{
string filename = Path.GetFileName(FileUpload1.FileName);
string path = Server.MapPath(ConfigurationManager.AppSettings["Path"]) + filename;
if (File.Exists(path))
{
ScriptManager.RegisterStartupScript(this, GetType(), "", "ConfirmBox();", true);
ExistPath = path;
Session["FileUpload1"] = FileUpload1;
Session["GridView1"] = GridView1;
}
else
{
SaveXml(path);
}
}
}
Javascript
<script language="javascript" type="text/javascript">
function ConfirmBox() {
if (confirm("Do you want to overrite")) {
PageMethods.FileExist(document.getElementById('<%=hfConfirmValue.ClientID %>').value);
}
}
</script>
The page method
[WebMethod(EnableSession = true)]
public static string FileExist(string confirm)
{
#region Save XML
string path = ExistPath;
FileUpload s = HttpContext.Current.Session["FileUpload1"] as FileUpload;
GridView g = HttpContext.Current.Session["GridView1"] as GridView;
s.SaveAs(path);
DataSet ds = new DataSet();
ds.ReadXml(Path.GetFullPath(path));
GlobalDS = ds;
g.DataSource = ds;
g.DataBind();
return "file updated";
#endregion
}
Related
I try to download a pdf file from my sql database.
I display list from database. My purpose is get pdf file from link.
Because of loop "for" I don't know how to get a correct path to download it.
///FRONTEND CODE
<tr v-for="not in notatki">
<td>{{not.NotatkaId}}</td>
<td>{{not.NotatkaName}}</td>
<td>{{not.Przedmiot}}</td>
<td>{{not.DateOfJoining}}</td>
<td><a href="http://localhost:37924/api/Notatki/{{not.NotatkaFileName}}" download>Download File</a></td>
<td>
///API CODE
public JsonResult SaveFile()
{
try
{
var httpRequest = Request.Form;
var postedFile = httpRequest.Files[0];
string filename = postedFile.FileName;
var physicalPath = _env.ContentRootPath + "/Notatki/" + filename;
using (var stream = new FileStream(physicalPath, FileMode.Create))
{
postedFile.CopyTo(stream);
}
return new JsonResult(filename);
}
It is link with error
[1]: https://i.stack.imgur.com/H5fqW.png
This is my simple program on downloading file from a varbinary string on click.
Controller:
public ActionResult Download(string StudentID, string SQNC)
{
string query = "exec spToGetVarbinaryString'" + StudentID + "','" + SQNC + "' ";
string dataStr = GlobalFunction.DataTableToJSON(GlobalFunction.TableFromMSSQL(dbname, query));
dynamic data = JsonConvert.DeserializeObject(dataStr);
byte[] file = data[0].ImgVarbinary;
return File(file, System.Net.Mime.MediaTypeNames.Application.Octet, (string)data[0].FileName);
}
how I download the File:
<a type="button" href="ControllerName/Download?StudentID=${row.StudentID}&SQNC=${row.SQNC}" class="btn btn-primary btn-sm active" role="button" aria-pressed="true">View File</a>
Now, I want the file instead of being downloaded on click, It will appear on tab or new. I tried the method of converting my Varbinary to Base64 string, but it doesnt read the PDF file for this example below.
From VarBinary to Base64 in SQL
update a set a.ImgStr=baze64
from #mytemptable
cross apply (select ImgVarbinary as '*' for xml path('')) T (baze64)
where a.ImgVarbinary is not null
Displaying Base64 PDF File (Display doesn't work)
<iframe width="500" height="500"
src="data:application/pdf;base64,<base64stringhere>"
I found a sample base64 data in this JSFiddle link, I tried it on local and it works.
Image example (left one: my base64 string. Right one: base64 from the js fiddle)
How can I do this and why my base64 string isn't working well? Thanks for answering.
add something like this on click event to read bytes....
public class LoadPdfFileHandler : IHttpHandler
{
public bool IsResuable => false;
public void ProcessRequest(HttpContext context)
{
string id = context.Request.QueryString["id"];
// TODO: Verify that the user is allowed to view the specified record.
using (var connection = new MySqlConnection("..."))
using (var command = new MySqlCommand("SELECT Data, ContentType FROM SomeTable WHERE ID = #ID", connection))
{
command.Parameters.AddWithValue("#ID", id);
connection.Open();
using (var reader = command.ExecuteReader(CommandBehavior.CloseConnection))
{
if (!reader.Read())
{
context.Response.StatusCode = 404;
return;
}
string contentType = (string)dr["ContentType"];
if (string.IsNullOrEmpty(contentType)) contentType = "application/octet-stream";
context.Response.ContentType = contentType;
byte[] bytes = (byte[])dr["Data"];
context.Response.BinaryWrite(bytes);
}
}
}
}
Then Write Frame Using this...
myiframe.Attributes["src"] = ResolveUrl("~/loadPdfFile.ashx?id=" + idOfTheRecordToLoad);
You can check Other Reference here image reference
I have worked in Web Application exporting datas in grid and I want to Save them Using Save as dialog box either in C#,Javascript.
function openDialog() {
var input = $(document.createElement('input'));
input.attr("type", "file")
input.trigger('click');
return false;
}
test
[HttpGet]
public async Task<HttpResponseMessage> Get(string fileHash)
{
//read file
byte[] fileData = await _deviceFileApiService.GetFileData(fileHash);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(fileData)
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = fileResource.FileName
};
return response;
}
on UI
save as
When user click on link, save as dialog will be appeared.
I have a MVC app that Im trying to use CKEditor with. One example I was looking at is here but there are many others. So far so good, but one section im still curious about, is the js that sends the selected file name back to the file upload dialog textbox.
<script type="text/javascript">
$(document).ready(function () {
$(".returnImage").click("click", function (e) {
var urlImage = $(this).attr("data-url");
window.opener.updateValue("cke_72_textInput", urlImage);
window.close();
});
});
</script>
In particular, the cke_72_textInput element. My example wasnt working initially, until I opened chrome dev tools and found the actual id of the textinput, which was in my case cke_76_textInput. Why the id change I wonder? Seems a little "fragile" to refer to a specific id like this? The above js code just takes the selected image file and returns it into the textbox of the fileupload dialog.
Is there something exposed that references this textbox element indirectly without specifying it by id (via the config for example)?
On view:
$(document).ready(function () {
CKEDITOR.replace('Text-area-name', {
filebrowserImageUploadUrl: '/Controller-name/UploadImage'
});
CKEDITOR.editorConfig = function (config) {
// Define changes to default configuration here. For example:
config.language = 'de';
// config.extraPlugins = 'my_own_plugin'; // if you have any plugin
// config.uiColor = '#AADC6E';
// config.image_previewText = CKEDITOR.tools.repeat(' Hier steht dann dein guter Text. ', 8 );
// config.contentsLanguage = 'de';
config.height = 350; // 350px, specify if you want a larger height of the editor
config.linkShowAdvancedTab = false;
config.linkShowTargetTab = false;
};
CKEDITOR.on('dialogDefinition', function (ev) {
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
ev.data.definition.resizable = CKEDITOR.DIALOG_RESIZE_NONE;
if (dialogName == 'link') {
var infoTab = dialogDefinition.getContents('info');
infoTab.remove('protocol');
dialogDefinition.removeContents('target');
dialogDefinition.removeContents('advanced');
}
if (dialogName == 'image') {
dialogDefinition.removeContents('Link');
dialogDefinition.removeContents('advanced');
var infoTab = dialogDefinition.getContents('info');
infoTab.remove('txtBorder');
infoTab.remove('txtHSpace');
infoTab.remove('txtVSpace');
infoTab.remove('cmbAlign');
}
});
}
On Contoller:
[HttpPost]
public ActionResult UploadImage(HttpPostedFileBase file, string CKEditorFuncNum, string CKEditor, string langCode)
{
if (file.ContentLength <= 0)
return null;
// here logic to upload image
// and get file path of the image
const string uploadFolder = "Assets/img/";
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath(string.Format("~/{0}", uploadFolder)), fileName);
file.SaveAs(path);
var url = string.Format("{0}{1}/{2}/{3}", Request.Url.GetLeftPart(UriPartial.Authority),
Request.ApplicationPath == "/" ? string.Empty : Request.ApplicationPath,
uploadFolder, fileName);
// passing message success/failure
const string message = "Image was saved correctly";
// since it is an ajax request it requires this string
var output = string.Format(
"<html><body><script>window.parent.CKEDITOR.tools.callFunction({0}, \"{1}\", \"{2}\");</script></body></html>",
CKEditorFuncNum, url, message);
return Content(output);
}
I had the same problem...a little frustrating that I couldn't find any official documentation, considering this seems like a common use case.
Anyways, take a look at the quick tutorial here: http://r2d2.cc/2010/11/03/file-and-image-upload-with-asp-net-mvc2-with-ckeditor-wysiwyg-rich-text-editor/. In case the link ever breaks, here's what I did.
[HttpPost]
public ActionResult UploadImage(HttpPostedFileBase upload, string ckEditorFuncNum)
{
/*
add logic to upload and save image here
*/
var path = "~/Path/To/image.jpg"; // Logical relative path to uploaded image
var url = string.Format("{0}://{1}{2}",
Request.Url.Scheme,
Request.Url.Authority,
Url.Content(path)); // URL path to uploaded image
var message = "Saved!"; // Optional
var output = string.Format("<script>window.parent.CKEDITOR.tools.callFunction({0}, '{1}', '{2}');</script>",
CKEditorFuncNum,
url,
message);
return Content(output);
}
Download a file by clicking a image button.
I've this link
I've been trying to download the files (two save icon image buttons). When i click the image it prompts to download zip file.
This is the tag as seen in page's VIEWSOURCE of buttons
<input type="image" name="ctl00$m$g_b265ad4d_cd49_41f3_a9f2_0090f0aa5504$ctl00$gvBidSetsFile$ctl02$ImageButton1" id="ctl00_m_g_b265ad4d_cd49_41f3_a9f2_0090f0aa5504_ctl00_gvBidSetsFile_ctl02_ImageButton1" title="Download" src="/SiteAssets/images/saveitem.gif" style="height:18px;width:18px;border-width:0px;">
WebClient client = new WebClient(BrowserVersion.FIREFOX_38);
HtmlPage homePage = null;
// Document doc = null;
String base="https://bidset.nycsca.org/SitePages/Obtain%20Solicitation.aspx?SN=16-15323D-1&ReqType=Solicitation&IsDlg=1&IsDlg=1";
try {
client.getOptions().setUseInsecureSSL(true);
client.setAjaxController(new NicelyResynchronizingAjaxController());
client.waitForBackgroundJavaScript(1000);
client.waitForBackgroundJavaScriptStartingBefore(1000);
client.getOptions().setThrowExceptionOnFailingStatusCode(false);
client.getOptions().setThrowExceptionOnScriptError(false);
homePage = client.getPage(base);
synchronized (homePage) {
homePage.wait(5000);
}
System.out.println("file Page : " + homePage.getUrl());
// Document dd = Jsoup.parse(homePage.asXml());
HtmlInput docs= homePage.getFirstByXPath("//input[#id='ctl00_m_g_b265ad4d_cd49_41f3_a9f2_0090f0aa5504_ctl00_gvBidSetsFile_ctl02_ImageButton1']");
homePage = bidDocs.click();
Questions:
As I get
HtmlInput docs = homePage.getFirstByXPath
("//input[#id='ctl00_m_g_b265ad4d_cd49_41f3_a9f2_0090f0aa5504_ctl00_gvBidSetsFile_ctl02_ImageButton1']");
Is it ok to perform,
homePage = bidDocs.click();
here clicking on the save icon downloads file.
I m confused how could I download this file with help of HTMLUNIT .
I want to download file in my local drive .
Is it possible to get url link of homepage after (homePage = bidDocs.click();)
i.e. store link , String docurl=get homePage's link . ????
If i could get the link I can use BufferedStream to download file .
File file = new File("C:/TRY/file/abc.zip");
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
in = new BufferedInputStream(new URL(docUrl).openStream());
fout = new FileOutputStream(file);
final byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
}
} finally {
if (in != null) {
in.close();
}
if (fout != null) {
fout.close();
}
}
I've to use HTMLUNIT here because it is javascript, iframe site.
Im thankful for you help.
Thank you verymuch.
Selecting the file tag
HtmlInput download = pageCheck.getByXPath("//input[#title='Download']");
and for streamming
download.click().getWebResponse().getContentAsStream()