spring mvc download file not showing extension - spring-mvc

I'm trying to let customers download sample excel file. Here is my code:
String path = UploadController.class.getResource("/com/medify/data/" + file).getFile();
response.setContentType("application/force-download");
response.setContentType("application/excel");
response.setHeader("Content-Disposition", "attachment; filename=" + file);
try{
File fi = new File(path);
InputStream in = new BufferedInputStream(new FileInputStream(fi));
ServletOutputStream out = response.getOutputStream();
IOUtils.copy(in, out);
response.flushBuffer();
return null;
}
catch(Exception ex){
return null;
}
The problem is the downloaded file never have file extension. The file is sample-doctor-uploads.xls and it exists in com/medify/data package.

You need to use proper content type. If your file has .xls extention you need to use -
response.contentType = "application/vnd.ms-excel"
and use the full file name with extention like-
response.setHeader "Content-disposition", "attachment;filename=fileNamewithExtention"

Related

is not a valid virtual path error

This is my code for downloading text file. But the server.transfer method is not able to resolve that path. It is giving "is not a valid virtual path error"
string filePath = #"D:/BCPResult/Cust_File.t`enter code here`xt";
Response.ContentType = "text/plain";
Response.AppendHeader("content-disposition",
"attachment; filename=" + filePath);
Response.TransmitFile(Server.MapPath(filePath));
Response.End();
Please guide me...
If your file path is not related to server you do not need Server.MapPath.
Also if you run your code in windows, path separator is \, not /.
This code must work:
string filePath = #"D:\BCPResult\Cust_File.txt";
Response.ContentType = "text/plain";
Response.AppendHeader("content-disposition", "attachment; filename=" + filePath);
Response.TransmitFile(filePath);
Response.End();
Use '\' (backslash) instead '/'.
string filePath = #"D:\BCPResult\Cust_File.txt";
or
string filePath = "D:\\BCPResult\\Cust_File.txt";
If You Are trying to access a file from the Remote URL or External URL like (https://www.example.com/)
then you have to Use for the web client like this
string url= "this is the URL of the file from where you want to access the file"
System.Net.WebClient webClient = new System.Net.WebClient();
byte[] bytes = webClient.DownloadData(url);
if (mimetype != null)
{
context.Response.ContentType = mimetype;
}
else
{
context.Response.ContentType = "Application/pdf";
}
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
context.Response.BinaryWrite(bytes);
context.Response.End();

ServletOutputStream closes prematurely

I wrote a servlet to download a file. it works well for some files, but for others the os closes prematurely, and I end up downloading a blank file.
File file = new File(fileName);
InputStream fis = new FileInputStream(file);
resp.setHeader("Content-Type", "text/plain");
resp.setHeader("Content-Disposition", "attachment; filename=\"" + fileName );
resp.setDateHeader("Expires",0);
resp.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
resp.setHeader("Pragma", "public");
resp.setContentLength((int) file.length());
resp.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
ServletOutputStream os = resp.getOutputStream();
byte[] bufferData = new byte[1024];
int read = 0;
while((read = fis.read(bufferData))!= -1){
System.out.println("read " + read + " chars");
os.write(bufferData, 0, read);
}
os.flush();
os.close();
fis.close();
when I debug, I can see it trying to write the first buffer worth of data into os, then on the browser side, the download dialog pops up with a blank file. in the servlet, I get a IOClosed on the next buffer write.
I tried using IOUtils.copy(fis, resp.getOutputStream());
get the same error.
any reason certain type of file data can force os to close prematurely? can I protect against it?

ASP.Net : system.io.packaging package "File contains corrupted data"

I am using system.io.packaging.package to create a package containing some files.
Purpose is to create an import/export functionnality.
I create the package like that :
// Create the compressed file.
using (FileStream outFile = File.Create(this.packageName))
{
using (Package Compress = Package.Open(outFile, FileMode.Create))
{
foreach (string file in Directory.GetFiles(Path.GetDirectoryName(this.packageName)))
{
FileInfo fi = new FileInfo(file);
// Prevent compressing hidden and already compressed files.
if ((File.GetAttributes(fi.FullName) & FileAttributes.Hidden) != FileAttributes.Hidden & fi.Extension != ".gz")
{
PackagePart packagePartDocument;
if (fi.Extension == ".xml")
{
packagePartDocument = Compress.CreatePart(PackUriHelper.CreatePartUri(new Uri(#"/" + Path.GetFileName(file), UriKind.Relative)), System.Net.Mime.MediaTypeNames.Text.Xml);
}
else
{
packagePartDocument = Compress.CreatePart(PackUriHelper.CreatePartUri(new Uri(#"/" + Path.GetFileName(file), UriKind.Relative)), System.Net.Mime.MediaTypeNames.Text.Plain);
}
using (FileStream inFile = fi.OpenRead())
{
inFile.CopyTo(packagePartDocument.GetStream());
}
Compress.CreateRelationship(packagePartDocument.Uri, TargetMode.Internal, fi.FullName);
}
}
}
}
and I read it like that :
using (Package zip = Package.Open(PackageStream, FileMode.Open, FileAccess.Read, FileShare.None))
{
Directory.CreateDirectory(Path.Combine(App.Configuration.TempDirectory, this.packageName.Split('.')[0]));
foreach (PackagePart file in zip.GetParts())
{
string fileName = Path.Combine(App.Configuration.TempDirectory, this.packageName.Split('.')[0], file.Uri.ToString().TrimStart('/'));
using (FileStream fileStream = new FileStream(fileName, FileMode.Create))
{
file.GetStream().CopyTo(fileStream);
}
}
}
My issue occurs when Package try to open the file
Package zip = Package.Open(PackageStream, FileMode.Open, FileAccess.Read, FileShare.None)
I have an error "File contains corrupted data"
I have done many tests over and over and I don't understand...
EDIT : The same code is working with an console applciation but not in a web application.
Finally I found my mistake :
When I return this generated package I return the package but the entire web page too.
Response.AddHeader("content-disposition", "attachment; filename=" + export.PackageName);
Response.ContentType = "application/octet-stream";
Response.WriteFile(export.PackageFullName);
So I corrected it by
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + export.PackageName);
Response.ContentType = "application/octet-stream";
Response.WriteFile(export.PackageFullName);
Response.Flush();
Response.End();
It works :)

Server not pointing to folder

i have a website on server. It has a button which triggers the downloading of a file(.zip/.doc) from that server.
But it is not pointing to that folder/file. How to resolve this issue??
It fails at this particular file...
public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed){
FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
}
I have not tried your code but this seems to work for me. you can make the rest dynamic.
string FileName = "test.zip";
string PathFile = "C:\project\download\test.zip";
var fileInfo = new System.IO.FileInfo(PathFile);
Response.ContentType = "application/zip";
Response.AddHeader("Content-Disposition", String.Format("attachment;filename=\"{0}\"", FileName));
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.WriteFile(PathFile);
Response.End();

File Download inside iframe

I'm using following method to download a file.on a button click inside a iframe.it's working fine in every browser except IE.can some one plz suggest me a sollution
private void DownloadToBrowser(string filePath)
{
try
{
FileInfo file = new FileInfo(filePath);
Context.Response.Clear();
Context.Response.ClearHeaders();
Context.Response.ClearContent();
Context.Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Context.Response.AddHeader("Content-Length", file.Length.ToString());
Context.Response.ContentType = "text/plain";
Context.Response.Flush();
Context.Response.TransmitFile(file.FullName);
Context.Response.End();
}
catch (Exception ex)
{
throw ex;
}
}
I would suggest removing the Context.Response.Flush(); line... I don't think it's necessary (as it will happen as part of Context.Response.End(); line), and maybe messing up how the browser receives the file on the next line.
Also, is the file you're transmitting definitely a plain-text file? If not, you'll need to provide a different Context.Response.ContentType();
You have most probably missed some HTTP response headers required by IE.
There is KB on microsoft web.
Also take a look at similar question on SO : PHP script to download file not working in IE
You could try something like this :
Context.Response.Buffer = true;
Context.Response.ContentType = "application/pdf";
Context.Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName );
Context.Response.OutputStream.Write(dataBytes ,0,FileContentLength);
Also try adding this to your aspx page :
<%# Page aspCompat="True" other attributes %>
For Understanding I m using Dataset,
For download as a Excel File
Use Namespace:
using System.IO;
using System.Data;
DataSet ds = new DataSet("Table");
ds.Tables.Add("Table1");
ds.Tables[0].Columns.Add("Field1");
ds.Tables[0].Columns.Add("Field2");
ds.Tables[0].Columns.Add("Field3");
ds.Tables[0].Rows.Add();
ds.Tables[0].Rows[0][0] = "1";
ds.Tables[0].Rows[0][1] = "2";
ds.Tables[0].Rows[0][2] = "3";
HttpResponse response = HttpContext.Current.Response;
// first let's clean up the response.object
response.Clear();
response.Charset = "";
// set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=sample.xls");
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// instantiate a datagrid
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables[0];
dg.DataBind();
dg.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
For Download as a Word File
Replace
response.ContentType = "application/msword";
response.AddHeader("Content-Disposition", "attachment;filename=sample.doc");

Resources