I need to download the selected files in a grid on download button click. I am using knokout.js and web api
Using the below given response I was able to download a single file
self.DownloadDoc = function () {
window.location.assign("http://localhost:8092/api/Document/GetResponse?id=" + self.selectedDocuments()[0]);
self.selectedDocuments.removeAll();
self.bindDocuments();
};
I tried looping this window.location.assign() code using for loop,but as it is synchronous call,its downloading only one file.
Html part
<span>Download</span><small></small>
Web Api code
[HttpGet]
public HttpResponseMessage GetResponse(string id)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
List<DocumentsModel> documents = _service.GetDocumentContent(Convert.ToInt32(id));
byte[] fileBytes = documents.FirstOrDefault().FileContent;
System.Net.Http.Headers.MediaTypeHeaderValue mediaType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
if (fileBytes != null)
response.Content = new ByteArrayContent(fileBytes);
response.Content.Headers.ContentType = mediaType;
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = documents.FirstOrDefault().FileLeafRef;
return response;
}
this part self.selectedDocuments()[0], looks like it will force download always only of first document.
Not sure what is your structure and output of selectedDocuments(),
for example, if it outputs array, with fileID nodes, maybe you should try with this:
<div data-bind="foreach: self.selectedDocuments()">
<span>Download</span><small></small>
</div>
then, you will have to pass param in function:
self.DownloadDoc = function (fileID) {
window.location.assign("http://localhost:8092/api/Document/GetResponse?id=" + fileID);
self.selectedDocuments.removeAll();
self.bindDocuments();
};
Related
I'm trying to edit a word document (docx file) using NodeJs on the cloud but it's not working .
Here's the steps followed by code :
Firstly, I upload the Word document (DOCX) to the Cloud using the code example given below:
let fileApi = groupdocs_editor_cloud.FileApi.fromConfig(configuration);
let resourcesFolder = 'C:\\Files\\sample.docx';
fs.readFile(resourcesFolder, (err, fileStream) => {
let request = new groupdocs_editor_cloud.UploadFileRequest("sample.docx", fileStream, myStorage);
fileApi.uploadFile(request);
});
As a result, the uploaded DOCX file will be available in the files section of my dashboard on the cloud.
Then I :
Create instances of the FileAPI and the EditAPI
Provide the input file path in the FileInfo
Create WordProcessingLoadOptions
Create LoadRequest with LoadOptions
Load a file with the load() method of EditAPI
Create DownloadFileRequest with loaded file
Download HTML document using downloadFile() method of FileAPI
Edit the downloaded HTML Document
Create UploadFileRequest
Upload HTML back using uploadFile() method of FileAPI
Provide WordProcessingSaveOptions to save in the DOCX
Create SaveRequest with SaveOptions
Save HTML back to DOCX using the save() method of Edit API
let editApi = groupdocs_editor_cloud.EditApi.fromKeys(clientId, clientSecret);
let fileApi = groupdocs_editor_cloud.FileApi.fromKeys(clientId, clientSecret);
// input file
let fileInfo = new groupdocs_editor_cloud.FileInfo();
fileInfo.filePath = "Sample.docx";
// define load options
let loadOptions = new groupdocs_editor_cloud.WordProcessingLoadOptions();
loadOptions.fileInfo = fileInfo;
loadOptions.outputPath = "output";
// create load request
let loadRequest = new groupdocs_editor_cloud.LoadRequest(loadOptions);
let loadResult = await editApi.load(loadRequest);
// download html document
let downloadRequest = new groupdocs_editor_cloud.DownloadFileRequest(loadResult.htmlPath);
let buf = await fileApi.downloadFile(downloadRequest);
let htmlString = buf.toString("utf-8");
// edit something...
htmlString = htmlString.replace("Title of the document", "Welcome");
htmlString = htmlString.replace("Subtitle #1", "Hello world");
// upload html back to storage
let uploadRequest = new groupdocs_editor_cloud.UploadFileRequest(loadResult.htmlPath, new Buffer.from(htmlString, "utf-8"));
await fileApi.uploadFile(uploadRequest);
// save html back to docx
let saveOptions = new groupdocs_editor_cloud.WordProcessingSaveOptions();
saveOptions.fileInfo = fileInfo;
saveOptions.outputPath = "output/edited.docx";
saveOptions.htmlPath = loadResult.htmlPath;
saveOptions.resourcesPath = loadResult.resourcesPath;
// create save request
let saveRequest = new groupdocs_editor_cloud.SaveRequest(saveOptions);
let saveResult = await editApi.save(saveRequest);
console.log("Document edited: " + saveResult.path);
The problem is that the final edited document that is supposed to be changed doesn't contain the changes i just made and i can't see any problem !!
I have a aurelia client that gets a image from my asp.net server via my API. The image is served from the server that holds a Emgu CV UMat var. With the following method in my controller i get the image and it is displayed correctly.
This method results in memory leakage and i can't seem to get to the orgin (not calling the method, means no leak):
Update, i tried Mawg's suggestion but when i close the stream it will not show the image. The leak is gone then but there is no image.
[System.Web.Http.HttpGet]
[System.Web.Http.Route("dummymethod3")]
public HttpResponseMessage Get2()
{
HttpResponseMessage response = new HttpResponseMessage();
try
{
Console.WriteLine("Get image 3");
ddEngine.sem.WaitOne();
var memoryStream = new MemoryStream();
ResultImage.Bitmap.Save(memoryStream, ImageFormat.Png);
memoryStream.Position = 0;
var result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StreamContent(memoryStream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
memoryStream.Close();
memoryStream.Dispose();
ddEngine.sem.Release();
return result;
}
catch
{
Console.WriteLine("Ex");
}
return response;
}
I have tried to call the collector at several places in the code like:
GC.Collect();
GC.WaitForPendingFinalizers();
When doing this it releases resources but the memory usege is slowly increasing. When not calling the get method there is no increase!
My client code looks like this:
updateImageSrc() {
let dt = new Date();
let baseUrl = "http://localhost:8080/api/status/dummymethod3";
this.imagePath = baseUrl + "?t=" + dt.getTime();
}
And the html
<img id="img" src.bind="imagePath"/>
Any suggestions are welcome!
How can show document file in iframe when i get the file name from database?My database table name is File and my viewmodel is MyFileModel.
public ActionResult Create(HttpPostedFileBase file)
{
try
{
if (ModelState.IsValid)
{
db.Files.Add(new File()
{
FileName = Path.GetFileName(file.FileName)
});
db.SaveChanges();
}
}
catch (Exception)
{
var error = "Sorry not save";
}
return Content("");
}
public FileStreamResult GetPDF()
{
var file = db.Files.Single(s => s.Id == 1);
FileStream fs = new FileStream(Server.MapPath(file.FileName), FileMode.Open, FileAccess.Read);
return File(fs, "application/pdf");
//return View(Server.MapPath("~/File/SegmentAdd.txt"));
//return File(fs,"text/plain");
}
<div id="frame">
<iframe src="#Url.Action("GetPDF","Home")" width="900px" height="500px"></iframe>
</div>
`
The answer which I am posting is all on an assumption, I do not have clear picture of your solution.
If you are not saving a physical file try to save it in a folder and then save the name in the DB OR try to save the entire path in the DB.
Method 1 :
If you are saving the file in a folder say File best way is to add a key in the web.config(.config file which is at the root) as follows
<add key="FilePath" value= "~/File/"/>
and then modify your C# code as follows
public FileStreamResult GetPDF()
{
var file = db.Files.Single(s => s.Id == 1);
string fileName = file.FileName;
string filePath = ConfigurationManager.AppSettings["FilePath"] + fileName;
FileStream fs = new FileStream(Server.MapPath(filePath), FileMode.Open, FileAccess.Read);
return File(fs,"text/plain"); // "text/plain" if your file content-type is text file
//return View(Server.MapPath("~/File/SegmentAdd.txt"));
//return File(fs,"text/plain");
}
Method 2 :
If you are saving the entire path then it makes coding much more simpler and you need not change the code you have written, just go ahead with the same.
Hope this would help you.
I think the way the pdf will open is dependent on the browser that the user uses.
You probably need something like: https://pdfobject.com/.
Good luck!
I want to embed a javascript snippet inside of a pdf file so that it will immediately print when it's opened from a browser window. To try and achieve this I'm following this example here.
I have created a helper class that has a static method to handle this task. I already have the pdf file path string ready to pass into the method. What I don't understand is how the output stream portion of this works. I would like the updated pdf to be saved to my servers hard drive. I do not want to stream it back to my browser. Any guidance would be greatly appreciated.
public class PdfHelper
{
public static void AddPrintFunction(string pdfPath, Stream outputStream)
{
PdfReader reader = new PdfReader(pdfPath);
int pageCount = reader.NumberOfPages;
Rectangle pageSize = reader.GetPageSize(1);
// Set up Writer
PdfDocument document = new PdfDocument();
PdfWriter writer = PdfWriter.GetInstance(document, outputStream);
document.Open();
//Copy each page
PdfContentByte content = writer.DirectContent;
for (int i = 0; i < pageCount; i++)
{
document.NewPage();
// page numbers are one based
PdfImportedPage page = writer.GetImportedPage(reader, i + 1);
// x and y correspond to position on the page
content.AddTemplate(page, 0, 0);
}
// Inert Javascript to print the document after a fraction of a second to allow time to become visible.
string jsText = "var res = app.setTimeOut(‘var pp = this.getPrintParams();pp.interactive = pp.constants.interactionLevel.full;this.print(pp);’, 200);";
//string jsTextNoWait = “var pp = this.getPrintParams();pp.interactive = pp.constants.interactionLevel.full;this.print(pp);”;
PdfAction js = PdfAction.JavaScript(jsText, writer);
writer.AddJavaScript(js);
document.Close();
}
}
For how to accomplish this task, please take a look at this and this SO posts.
Basically you should have something like this:
var pdfLocalFilePath = Server.MapPath("~/sourceFile.pdf");
var outputLocalFilePath = Server.MapPath("~/outputFile.pdf");
using (var outputStream = new FileStream(outputLocalFilePath, FileMode.CreateNew))
{
AddPrintFunction(pdfLocalFilePath, outputStream);
outputStream.Flush();
}
Hi i have uploaded file to one amazon s3 server,how can i read excel file and want to send excel data to database.
my code is
<script type="text/javascript">
var obj = null;
$(function () {
$('#fileupload').fileupload({
replaceFileInput: false,
formData: function (form) {
return [{ name: "name1", value: "value1" }, { name: "name2", value: "value2"}];
$('#btnGo').click(function () {
obj.submit();
});
});
</script>
And my ashx page, where i need to read excel data
public class AjaxFileHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var file = context.Request.Files[0];
string fileName=fileName = Guid.NewGuid().ToString() + file.FileName;
Stream streamContentFile = context.Request.Files[0].InputStream;
var iFileSize = context.Request.Files[0].ContentLength;
byte[] data = new byte[iFileSize];
int bytes_read = 0;
while (bytes_read < iFileSize)
{
int bytes_read_this_iteration = streamContentFile.Read(data, bytes_read, iFileSize - bytes_read);
streamContentFile.Close();
streamContentFile.Dispose();
CommonBLL.UploadTemporaryFilesToS3Bucket(fileName, data);
//Here i need to read excel code can you provide how to do that pleas
}
I would use open source libraries for excel, EPPlus (xslx) or NPOI (xls). They are very easy to use, and I am using EPPlus for numerous excel imports / exports and it's working great. These libraries have no external dependancies, and you can use it on server side.
you need two things:
a Driver that allows code to read Excel content
access to this file
a query over excel data
In this sample:
I use ACE (Microsoft Access Database Engine) driver, that must be installed on the server
the file is in App_Data folder (in your case the file should be rached CommonBLL library, i suppose)
the query is an UPDATE query; you can replace with a SELECT or INSERT query, using common DB SNippets.
string fileName= Server.MapPath( "~/App_Data/MyFile.xls");
string sheetName= "Sheet1";
string connString = string.Format(
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=No'"
, fileName);
string command = string.Format("UPDATE [{0}${1}:{1}] SET F1='{2}'", sheetName,cellName, cellValue);
using (OleDbConnection oledbConn = new OleDbConnection(connString))
{
oledbConn.Open();
using (OleDbCommand cmd = new OleDbCommand(command, oledbConn))
cmd.ExecuteNonQuery();
oledbConn.Close();
}