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
Related
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 need to retrieve and then display a pdf file. I have working code that retrieves an image from a database, converts to .pdf, and returns that as JSON. I can display this just fine in chrome by making it into a blob, but because IE refuses to support data URIs, I figure I could generate a temporary pdf file on the server and then link to it like this, as suggested elsewhere on the site:
<iframe style="width: 100%; height: 100%;" frameborder="0" scrolling="no" id="myFrame">
<p>It appears your web browser doesn't support iframes.</p>
</iframe>
And then set the src attribute in .js file:
$('#myFrame').attr('src', 'http://www.example.com/tempPDFname.pdf');
How would I generate this file and make it available on server (C#) so I can set the src attribute?
"GhostScript" may help you. Please check the linkes How to use Ghostscript for converting PDF to Image and https://ghostscriptnet.codeplex.com/
How to return a PDF from a Web API application
[HttpGet]
[Route("documents/{docid}")]
public HttpResponseMessage Display(string docid) {
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest);
var documents = reader.GetDocument(docid);
if (documents != null && documents.Length == 1) {
var document = documents[0];
docid = document.docid;
byte[] buffer = new byte[0];
//generate pdf document
MemoryStream memoryStream = new MemoryStream();
MyPDFGenerator.New().PrintToStream(document, memoryStream);
//get buffer
buffer = memoryStream.ToArray();
//content length for use in header
var contentLength = buffer.Length;
//200
//successful
var statuscode = HttpStatusCode.OK;
response = Request.CreateResponse(statuscode);
response.Content = new StreamContent(new MemoryStream(buffer));
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
response.Content.Headers.ContentLength = contentLength;
ContentDispositionHeaderValue contentDisposition = null;
if (ContentDispositionHeaderValue.TryParse("inline; filename=" + document.Name + ".pdf", out contentDisposition)) {
response.Content.Headers.ContentDisposition = contentDisposition;
}
} else {
var statuscode = HttpStatusCode.NotFound;
var message = String.Format("Unable to find resource. Resource \"{0}\" may not exist.", docid);
var responseData = responseDataFactory.CreateWithOnlyMetadata(statuscode, message);
response = Request.CreateResponse((HttpStatusCode)responseData.meta.code, responseData);
}
return response;
}
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
}
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()
i am reading one xls file through java script.
function upload1()
{
var ControlCn = new ActiveXObject("ADODB.Connection");
var Conn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = C:\\TEST.xls;Persist Security Info=False;Extended Properties=Excel 8.0;";
ControlCn.Open(Conn);
var rs = new ActiveXObject("ADODB.Recordset");
var SQL = "select * from [Sheet1$]";
rs.Open(SQL, ControlCn);
if(rs.bof)
{
document.write('No Data Avaliable');
}
if(!rs.bof)
{
rs.MoveFirst()
while(!rs.eof)
{
for(var i=0; i!= rs.fields.count; ++i)
{
document.write(rs.fields(i).value + ", ");
}
document.write("<br />");
rs.MoveNext()
}
}
rs.Close();
ControlCn.Close();
}
In the third line we are giving path of the xls file that we want to read. Is it possible to dynamically fetch the excel file through one browse button<input type="flie" ...
You can try the below:
<input type="file" id="myexcelfile"/>
once the user browses the file, then you can get the path as below:
var filepath=document.getElementById("myexcelfile").value;
You can use the "filepath" variable in your code for passing the excel sheet name