Download File Servlet - File Content contains binary - servlets

I had tried to develop a servlet that allow user to download file but it allow user to download the file but the file content contains binary garbage and not human readable. May I know what could be the reason ?
Code
int length = -1, index = 0;
byte[] buffer = null;
String attachmentPath = null, contentType = null, extension = null;
File attachmentFile = null;
BufferedInputStream input = null;
ServletOutputStream output = null;
ServletContext context = null;
attachmentPath = request.getParameter("attachmentPath");
if (attachmentPath != null && !attachmentPath.isEmpty()) {
attachmentFile = new File(attachmentPath);
if (attachmentFile.exists()) {
response.reset();
context = super.getContext();
contentType = context.getMimeType(attachmentFile.getName());
response.setContentType(contentType);
response.addHeader("content-length", String.valueOf(attachmentFile.length()));
response.addHeader("content-disposition", "attachment;filename=" + attachmentFile.getName());
try {
buffer = new byte[AttachmentTask.DEFAULT_BUFFER_SIZE];
input = new BufferedInputStream(new FileInputStream(attachmentFile));
output = response.getOutputStream();
while ((length = input.read(buffer)) != -1) {
output.write(buffer, 0, length);
index += length;
// output.write(length);
}
output.flush();
input.close();
output.close();
} catch (FileNotFoundException exp) {
logger.error(exp.getMessage());
} catch (IOException exp) {
logger.error(exp.getMessage());
}
} else {
try {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} catch (IOException exp) {
logger.error(exp.getMessage());
}
}
It is relate to writing file as binary or text mode or browser settings?
Please help.
Thanks.

The problem is not in the code given so far. You're properly using InputStream/OutputStream instead of a Reader/Writer to stream the file.
The cause of the problem is more likely in the way how you created/saved the file. This problem will manifest when you've used a Reader and/or Writer which is not been instructed to use the proper character encoding for the characters being read/written. Perhaps you're creating an upload/download service and the fault was in the upload process itself?
Assuming that the data is in UTF-8, you should have created the reader as follows:
Reader reader = new InputStreamReader(new FileInputStream(file), "UTF-8"));
and the writer as follows:
Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
But if you actually don't need to manipulate the stream on a per-character basis, but just wanted to transfer the data unmodified, then you should actually have used InputStream/OutputStream all the time.
See also:
Unicode - How to get the characters right?

Related

System.IO.File.ReadAllBytes Access to the path denied

Am running the project on the visual studio 2015, When I tried to read the PDF its giving me the following error;
Access to the path 'E:\FILE\FILEUPLOAD\InnerFile\File' is denied.
Function Defination
var cd = new System.Net.Mime.ContentDisposition { FileName = "PDF.pdf", Inline = true };
string contentType = MimeMapping.GetMimeMapping("PDF.pdf");
Response.AppendHeader("Content-Disposition", cd.ToString());
var innerPath = "InnerFile/File" ;
FileInfo fi = new FileInfo(PDFUploadRootPath + innerPath + "/PDF.pdf");
byte[] bytes = System.IO.File.ReadAllBytes(PDFUploadRootPath + innerPath);
return File(bytes, contentType);
NOTE:
Given Full permission to user
Physically File Exists
I dont understand what to do now please help!
Your FileInfo instance indeed references 'E:\FILE\FILEUPLOAD\InnerFile\File\PDF.pdf':
FileInfo fi = new FileInfo(PDFUploadRootPath + innerPath + "/PDF.pdf");
but when trying to read the file contents you forgot the file name and only use the path 'E:\FILE\FILEUPLOAD\InnerFile\File':
byte[] bytes = System.IO.File.ReadAllBytes(PDFUploadRootPath + innerPath);
Thus, also add the file name for reading all file bytes:
byte[] bytes = System.IO.File.ReadAllBytes(PDFUploadRootPath + innerPath + "/PDF.pdf");
Furthermore, as others have mentioned in comments, you should really use Path.Combine to glue path parts together, not simple string concatenation...
Try using FileStream instead of byte array for reading the pdf file.
FileStream templateFileStream = File.OpenRead(filePath);
return templateFileStream;
Also check (through code) if user has write permission to directory or path:
public static bool HasUserWritePermission(String path, String NtAccountName)
{
DirectoryInfo di = new DirectoryInfo(path);
DirectorySecurity acl = di.GetAccessControl(AccessControlSections.All);
AuthorizationRuleCollection rules = acl.GetAccessRules(true, true, typeof(NTAccount));
Boolean hasPermission = false;
//Go through the rules returned from the DirectorySecurity
foreach (AuthorizationRule rule in rules)
{
//If we find one that matches the identity we are looking for
if (rule.IdentityReference.Value.Equals(NtAccountName, StringComparison.CurrentCultureIgnoreCase))
{
//Cast to a FileSystemAccessRule to check for access rights
if ((((FileSystemAccessRule)rule).FileSystemRights & FileSystemRights.WriteData) > 0)
{
hasPermission = true;
}
else
{
hasPermission = false;
}
}
}
return hasPermission;
}

Microsoft Word Docx Download Attachment Error

I have doc or docx document saved in Unix directory and integrate with web page which allow user to download the attachment. I have following code to stream the character and saves as Word document with correct MIME type but why when open it shows garbage character. It is relate to character encoding problem. How to solve this? Should I use docx4j?
String fullfilename = filename;
File f = new File(fullfilename);
int length = 0;
ServletOutputStream op = response.getOutputStream();
ServletContext context = getContext();
String mimetype = context.getMimeType(fullfilename);
response.setContentType((mimetype != null) ? mimetype
: "application/x-download");
response.setContentLength((int) f.length());
response.setHeader("Content-Disposition", "attachment;filename="
+ filename);
byte[] bbuf = new byte[fullfilename.length()];
DataInputStream in = new DataInputStream(new FileInputStream(f));
while ((in != null) && ((length = in.read(bbuf)) != -1)) {
op.write(bbuf, 0, length);
}
in.close();
op.flush();
op.close();
Please help. Thanks.
Thread closed after setting the correct mime type.

File not found exception once deployed to Server

I am using the below code to Upload an Image file to a SharePoint Document Library. The code works fine locally but once deployed to server, i get the Exception as file not found.
String fileToUpload = FlUpldImage.PostedFile.FileName; //#"C:\Users\admin.RSS\Desktop\Photos\me_skype.jpg";
String documentLibraryName = "SiteAssets";
if (!System.IO.File.Exists(fileToUpload))
throw new FileNotFoundException("File not found.", fileToUpload);
SPFolder myLibrary = web.Folders[documentLibraryName];
// Prepare to upload
Boolean replaceExistingFiles = true;
String fileName = CheckStringNull(txtFirstName.Text) + CheckStringNull(txtLastName.Text) + CheckDateNull(txtDOB) + System.IO.Path.GetFileName(fileToUpload); ;
if (fileName.Contains('/'))
{
fileName = fileName.Replace("/", "");
}
if (fileName.Contains(':'))
{
fileName = fileName.Replace(":", "");
}
FileStream fileStream = File.OpenRead(fileToUpload);
//Upload document
SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);
string url = site.ToString() + "/" + spfile.ToString();
if (url.Contains("="))
{
url = url.Split('=')[1];
}
//Commit
myLibrary.Update();
The string fileupload contains URL as C:\Users\admin.RSS\Desktop\Photos\me.jpg This URL is actually the client system and the server side code throws exception as file not found. How to handle this issue?
UPDATE:
I removed the lines of code that checks if the file exists and now i get the exeption on FileStream fileStream = File.OpenRead(fileToUpload); as c:\windows\system32\inetsrv\20120605_133145.jpg cold not be found
Kindly help. Thank You
if (this.fuAvatarUpload.HasFile && this.fuAvatarUpload.PostedFile.FileName.Length > 0)
{
string extension = Path.GetExtension(file.FileName).ToLower();
string mimetype;
switch (extension)
{
case ".png":
case ".jpg":
case ".gif":
mimetype = file.ContentType;
break;
default:
_model.ShowMessage("We only accept .png, .jpg, and .gif!");
return;
}
if (file.ContentLength / 1000 < 1000)
{
Image image = Image.FromStream(file.InputStream);
Bitmap resized = new Bitmap(image, 150, 150);
byte[] byteArr = new byte[file.InputStream.Length];
using (MemoryStream stream = new MemoryStream())
{
resized.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
byteArr = stream.ToArray();
}
file.InputStream.Read(byteArr, 0, byteArr.Length);
profile.ImageUrl = byteArr;
profile.UseGravatar = false;
profileService.UpdateProfile(profile);
this._model.ShowApprovePanel();
}
else
{
_model.ShowMessage("The file you uploaded is larger than the 1mb limit. Please reduce the size of your file and try again.");
}
}
Saving the file physically onto server and than working on the same helped me resolve my issue.

Biztalk 2010 Custom Pipeline Component returns binary

I have created a custom pipeline component which transforms a complex excel spreadsheet to XML. The transformation works fine and I can write out the data to check. However when I assign this data to the BodyPart.Data part of the inMsg or a new message I always get a routing failure. When I look at the message in the admin console it appears that the body contains binary data (I presume the original excel) rather than the XML I have assigned - see screen shot below. I have followed numerous tutorials and many different ways of doing this but always get the same result.
My current code is:
public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg)
{
//make sure we have something
if (inmsg == null || inmsg.BodyPart == null || inmsg.BodyPart.Data == null)
{
throw new ArgumentNullException("inmsg");
}
IBaseMessagePart bodyPart = inmsg.BodyPart;
//create a temporary directory
const string tempDir = #"C:\test\excel";
if (!Directory.Exists(tempDir))
{
Directory.CreateDirectory(tempDir);
}
//get the input filename
string inputFileName = Convert.ToString(inmsg.Context.Read("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties"));
swTemp.WriteLine("inputFileName: " + inputFileName);
//set path to write excel file
string excelPath = tempDir + #"\" + Path.GetFileName(inputFileName);
swTemp.WriteLine("excelPath: " + excelPath);
//write the excel file to a temporary folder
bodyPart = inmsg.BodyPart;
Stream inboundStream = bodyPart.GetOriginalDataStream();
Stream outFile = File.Create(excelPath);
inboundStream.CopyTo(outFile);
outFile.Close();
//process excel file to return XML
var spreadsheet = new SpreadSheet();
string strXmlOut = spreadsheet.ProcessWorkbook(excelPath);
//now build an XML doc to hold this data
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(strXmlOut);
XmlDocument finalMsg = new XmlDocument();
XmlElement xEle;
xEle = finalMsg.CreateElement("ns0", "BizTalk_Test_Amey_Pipeline.textXML",
"http://tempuri.org/INT018_Workbook.xsd");
finalMsg.AppendChild(xEle);
finalMsg.FirstChild.InnerXml = xDoc.FirstChild.InnerXml;
//write xml to memory stream
swTemp.WriteLine("Write xml to memory stream");
MemoryStream streamXmlOut = new MemoryStream();
finalMsg.Save(streamXmlOut);
streamXmlOut.Position = 0;
inmsg.BodyPart.Data = streamXmlOut;
pc.ResourceTracker.AddResource(streamXmlOut);
return inmsg;
}
Here is a sample of writing the message back:
IBaseMessage Microsoft.BizTalk.Component.Interop.IComponent.Execute(IPipelineContext pContext, IBaseMessage pInMsg)
{
IBaseMessagePart bodyPart = pInMsg.BodyPart;
if (bodyPart != null)
{
using (Stream originalStrm = bodyPart.GetOriginalDataStream())
{
byte[] changedMessage = ConvertToBytes(ret);
using (Stream strm = new AsciiStream(originalStrm, changedMessage, resManager))
{
// Setup the custom stream to put it back in the message.
bodyPart.Data = strm;
pContext.ResourceTracker.AddResource(strm);
}
}
}
return pInMsg;
}
The AsciiStream used a method like this to read the stream:
override public int Read(byte[] buffer, int offset, int count)
{
int ret = 0;
int bytesRead = 0;
byte[] FixedData = this.changedBytes;
if (FixedData != null)
{
bytesRead = count > (FixedData.Length - overallOffset) ? FixedData.Length - overallOffset : count;
Array.Copy(FixedData, overallOffset, buffer, offset, bytesRead);
if (FixedData.Length == (bytesRead + overallOffset))
this.changedBytes = null;
// Increment the overall offset.
overallOffset += bytesRead;
offset += bytesRead;
count -= bytesRead;
ret += bytesRead;
}
return ret;
}
I would first of all add more logging to your component around the MemoryStream logic - maybe write the file out to the file system so you can make sure the Xml version is correct. You can also attach to the BizTalk process and step through the code for the component which makes debugging a lot easier.
I would try switching the use of MemoryStream to a more basic custom stream that writes the bytes for you. In the BizTalk SDK samples for pipeline components there are some examples for a custom stream. You would have to customize the stream sample so it just writes the stream. I can work on posting an example. So do the additional diagnostics above first.
Thanks,

How to convert array of byte to original file (to provide download of file)

I m using Opendialogbox to read the file. Then stored the file in byte[] array.
file --> byte []
byte[] --> stored on SQL AZure in varbinary(max) field.
Here is my code:
OpenFileDialog ofd = new OpenFileDialog();
if ((bool)ofd.ShowDialog())
{
FileStream fileStream = ofd.File.OpenRead());
byte[] buffer = new byte[fileStream.Length];
int read = 0;
using (BinaryReader binaryReader = new BinaryReader(fileStream))
{
do
{
read = binaryReader.Read(buffer, 0, Convert.ToInt32(fileStream.Length));
// Stored the File in byte[] Array buffer
} while (read > 0);
}
}
Now I want to convert this byte array to the original file (like .doc,.txt,jpeg). i know the extension in which file is to be convert.
SQL AZure ---> byte[] // done
byte[] ---> to original file. // Problem
Please give solution to download the file.
One way - not necessarily the best - is as follows:
using (MemoryStream ms = new MemoryStream(theBytes))
{
using (FileStream fs = new FileStream(string.Format("C:\\tempfile.{0}", theExtension)))
{
ms.WriteTo(fs);
}
}
namespace FileSaveDialogDemo
{
public partial class MainPage : UserControl
{
#region Fields
SaveFileDialog dialog= new SaveFileDialog();
#endregion
#region Constructors
public MainPage()
{
InitializeComponent();
this.dialog = new SaveFileDialog();
try
{
this.dialog.DefaultExt = ".txt";
this.dialog.Filter = "Text Files|*.txt|Log Files|*.log|All Files|*.*";
this.dialog.FilterIndex = 2;
}
catch ( Exception ex )
{
this.tblError.Text = "Error configuring SaveFileDialog: " + ex.Message;
}
}
#endregion
private void btnSaveFile_Click( object sender, RoutedEventArgs e )
{
bool? dialogResult = this.dialog.ShowDialog();
if ( dialogResult == true )
{
try
{
byte[] fileBytes; // your varbinary file from database
using (Stream fs = (Stream)dialog.OpenFile())
{
fs.Write(fileBytes, 0, fileBytes.Length);
fs.Close();
lblMsg.Content = "File successfully saved!";
}
}
catch ( Exception ex )
{
this.tblError.Text = "Error calling service: " + ex.Message;
}
}
} // End of Function
}// End of MainPage class
}
It seems the issue you have has probably nothing to do with saving a binary file; it is more likely a basic security issue. Try saving to a path on which you have programmatic write access. For example, try saving to your My Documents directory instead of C:. Try using the Environment.SpecialFolder enumeration like this, and append the file name + extension.
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
You have a number of other ways to work around this issue, including starting Visual Studio in Elevated Mode (run as Administrator), and/or allow "Everyone" write access to your C:\ drive. But I wouldn't recommend these techniques necessarily; consider saving to a folder where the security settings are lower than c:\, such as My Documents.

Resources