In FormFile getFileDate() replacement in Struts2 is needed? - struts2

FormFile getFileData() replacement in struts 2 is needed.
whether FileUpload is replacement for FormFile and also for getFileData()??
FileUpload myFile = fileImportForm.getTheFile();
byte[] fileData = myFile.getFileData();

Related

How to return local pdf file to browser to save or open using asp.net mvc [duplicate]

This question already has answers here:
Returning a file to View/Download in ASP.NET MVC
(9 answers)
Closed 7 years ago.
I want to know how can i prompt user to download pdf file.
I have below code but it is not returning anything.
public ActionResult DownloadAssetClassGuide()
{
string folder = #"C:\NewFolder";
string file = "xyz.pdf";
string fullPath = Path.Combine(folder, file);
byte[] fileBytes = System.IO.File.ReadAllBytes(fullPath);
return File(fileBytes, "application/pdf", file);
}
am i missing something?
Any path to a file or a folder should first got mapped to the server because you are using a virtual path. Try to map the path to the server first using
HttpContext.Current.Server.MapPath:
FileInfo fInfo = new FileInfo(Server.MapPath(fullPath));
FileStream fileStream = new FileStream(fullPath, FileMode.Open, FileAccess.Read);
BinaryReader reader = new BinaryReader(fileStream);
byte[] fileBytes = reader.ReadBytes((int)fInfo.Length);
This method worked with me when I face same issue

I want to extract text from Ms word file in asp.net mvc?

I am new in Asp.net mvc and this is my first web based application in which i will extract text from word file and extract grammatical mistakes. but don't know how i can extract text from word file?
In ASP.NET a good way to work with Word documents is the Open XML SDK, because it doesnt need a word installation on the server.
You habe to install the Open XML SDK and add a references to DocumentFormat.OpenXml.dll and WindowsBase.dll to your project.
Then you can open your document and read/replace text like this:
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
class WordTest
{
public static void ReplaceTextInWordDoc()
{
string filepath = "C:\\Tmp\\MyWordDoc.docx";
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(filepath, true))
{
Body body = wordDoc.MainDocumentPart.Document.Body;
foreach (var paragraph in body.Elements<Paragraph>())
{
foreach (var run in paragraph.Elements<Run>())
{
foreach (var text in run.Elements<Text>())
{
if (text.Text.Contains("old"))
text.Text = text.Text.Replace("old", "new");
}
}
}
}
}
}

iTextSharp creating file in memory resulting corrupted file

I am trying to create a pdf file in MVC using iTextSharp. I do have a following simple used case. File is getting created but when I open the PDF I am getting error file is corrupted unable to open the file. Any idea/help ?
My Controller code is a follows
public FileStreamResult GetPdfMemory()
{
iTextSharp.text.Document doc = new iTextSharp.text.Document();
MemoryStream mem = new MemoryStream();
PdfWriter pdfWriter = PdfWriter.GetInstance(doc, mem);
//pdfWriter.CloseStream = false;
doc.Open();
doc.Add(new Paragraph("Charts"));
mem.Position = 0;
FileStreamResult fileStreamResult = new FileStreamResult(mem, System.Net.Mime.MediaTypeNames.Application.Pdf)
{
FileDownloadName = "chart_" + ".PDF"
};
return fileStreamResult;
}
View :
#Html.ActionLink("Pdf Memory", "GetPdfMemory", "Home", null, new { id = "download"})
FYI : When I try to use FileStream instead of MemoryStream all works fine. But I need to create PDF using memorystream.
You manipulate (mem.Position = 0) and use (new FileStreamResult(mem, ...)) the MemoryStream before signalling iTextSharp that it can finalize the document. Thus, depending on whether implicit destruction of the Document and the PdfWriter or the use of the data in the memory stream comes first, you either have a PDF missing its closing parts or the closing parts (being written after you reposition the memory stream) overwriting the start of the data.
To signal to iTextSharp that it can finalize the document, please call doc.Close() before manipulating the memory stream or alternatively use the Document in a using block, e.g.:
using (MemoryStream ms = new MemoryStream()) {
// step 1
using (Document document = new Document()) {
// step 2
PdfWriter.GetInstance(document, ms);
// step 3
document.Open();
// step 4
document.Add(new Paragraph("HelloWorldMemory"));
}
HttpContext.Current.Response.BinaryWrite(ms.ToArray());
}
(shamelessly copied from the sample HelloWorldMemory.cs from the Webified iTextSharp Examples) for iText in Action — 2nd Edition)
Using using implicitly causes the Document to be closed.

How to get original file from Struts Multipart Request Wrapper

Can any one please help me how to get the real file name from Struts2 MultiPartRequestWrapper.
MultiPartRequestWrapper multiWrapper =
(MultiPartRequestWrapper) ServletActionContext.getRequest();
Enumeration fileParameterNames = multiWrapper.getFileParameterNames();
if(fileParameterNames.hasMoreElements()){
String inputValue = (String) fileParameterNames.nextElement();
File[] files = multiWrapper.getFiles(inputValue);
for (File cf : files) {
System.out.println(cf.getParentFile().getName());
System.out.println("cf is : " + cf.getName());
System.out.println("cf is : " + cf.toURI().getPath());
File.createTempFile(cf.getName(),"");
}
}
I can see original file name, type, size from "fileParameterNames" but when get file I can only see tempfile with upload_xxxxxxxxx.tmp.
How can I get original file name from the File.
Advance thanks for your help.
Why are you doing all that?
See the file upload FAQ and details pages. All you need to do is provide the appropriate action properties:
public void setUploaded(File myDoc);
public void setUploadedContentType(String contentType);
public void setUploadedFileName(String filename);
and use the file upload interceptor, which is included in the default stack.
Note that different browsers send different information; some only send the original filename, while some send the complete path.
You have to use : multiWrapper.getFileNames("file")[0]
Where "file" is the name of the file control.
var fd = new FormData();
fd.append('file', files[i]);

Open xml replace text from word file and return memory stream using MVC

I have an word file that contain my specified pattern text {pattern} and I want to replace those pattern with new my string which was read from database. So I used open xml read stream from my docx template file the replace my pattern string then returned to stream which support to download file without create a temporary file. But when I opened it generated me error on docx file. Below is my example code
public ActionResult SearchAndReplace(string FilePath)
{
MemoryStream mem = new MemoryStream(System.IO.File.ReadAllBytes(FilePath));
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(mem, true))
{
string docText = null;
using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
{
docText = sr.ReadToEnd();
}
Regex regexText = new Regex("Hello world!");
docText = regexText.Replace(docText, "Hi Everyone!");
//Instead using this code below to write text back the original file. I write new string back to memory stream and return to a stream download file
//using (StreamWriter sw = new //StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
//{
// sw.Write(docText);
//}
using (StreamWriter sw = new StreamWriter(mem))
{
sw.Write(docText);
}
}
mem.Seek(0, SeekOrigin.Begin);
return File(mem, "application/octet-stream","download.docx"); //Return to download file
}
Please suggest me any solutions instead read a text from a word file and replace those expected pattern text then write data back to the original file. Are there any solutions replace text with WordprocessingDocument libary? How can I return to memory stream with validation docx file format?
The approach you are taking is not correct. If, by chance, the pattern you are searching for matches some Open XML markup, you will corrupt the document. If the text you are searching for is split over multiple runs, your search/replace code will not find the text and will not operate correctly. If you want to search and replace text in a WordprocessingML document, there is a fairly easy algorithm that you can use:
Break all runs into runs of a single
character. This includes runs that
have special characters such as a
line break, carriage return, or hard
tab.
It is then pretty easy to find a
set of runs that match the characters
in your search string.
Once you have identified a set of runs that match,
then you can replace that set of runs
with a newly created run (which has
the run properties of the run
containing the first character that
matched the search string).
After replacing the single-character runs
with a newly created run, you can
then consolidate adjacent runs with
identical formatting.
I've written a blog post and recorded a screen-cast that walks through this algorithm.
Blog post: http://openxmldeveloper.org/archive/2011/05/12/148357.aspx
Screen cast: http://www.youtube.com/watch?v=w128hJUu3GM
-Eric
string sourcepath = HttpContext.Server.MapPath("~/File/Form/s.docx");
string targetPath = HttpContext.Server.MapPath("~/File/ExportTempFile/" + DateTime.Now.ToOADate() + ".docx");
System.IO.File.Copy(sourcepath, targetPath, true);
using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(targetPath, true))
{
string docText = null;
using (StreamReader sr = new StreamReader(wordDocument.MainDocumentPart.GetStream()))
{
docText = sr.ReadToEnd();
}
Regex regexText = new Regex("Hello world!");
docText = regexText.Replace(docText, "Hi Everyone!");
byte[] byteArray = Encoding.UTF8.GetBytes(docText);
MemoryStream stream = new MemoryStream(byteArray);
wordDocument.MainDocumentPart.FeedData(stream);
}
MemoryStream mem = new MemoryStream(System.IO.File.ReadAllBytes(targetPath));
return File(mem, "application/octet-stream", "download.docx");
Writing directly to the word document stream will indeed corrupt it.
You should instead write to the MainDocumentPart stream, but you should first truncate it.
It looks like MainDocumentPart.FeedData(Stream sourceStream) method will do just that.
I haven't tested it but this should work.
public ActionResult SearchAndReplace(string FilePath)
{
MemoryStream mem = new MemoryStream(System.IO.File.ReadAllBytes(FilePath));
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(mem, true))
{
string docText = null;
using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
{
docText = sr.ReadToEnd();
}
Regex regexText = new Regex("Hello world!");
docText = regexText.Replace(docText, "Hi Everyone!");
using (MemoryStream ms = new MemoryStream())
{
using (StreamWriter sw = new StreamWriter(ms))
{
sw.Write(docText);
}
ms.Seek(0, SeekOrigin.Begin);
wordDoc.MainDocumentPart.FeedData(ms);
}
}
mem.Seek(0, SeekOrigin.Begin);
return File(mem, "application/octet-stream","download.docx"); //Return to download file
}

Resources