[WebMethod()]
public void GetFileByDocumentNumber(string DocumentNumber)
{
string FilePath = GetFile(DocumentNumber);
string FullPath = ConfigurationManager.AppSettings["FilePath"] + FilePath;
DownloadToBrowser(FullPath);
}
private void DownloadToBrowser(string filePath)
{
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();
}
I'm using above code for my web service in order to download a file from the server.it's working fine in the local machine but when i host my webservice on a server and try to consume the service it gives the following error
Client found response content type of 'text/plain', but expected 'text/xml'.
whats the reason for this error?
You should have to return a file content via WebMethod.
[WebMethod()]
public string GetFileByDocumentNumber(string DocumentNumber)
{
string FilePath = GetFile(DocumentNumber);
string FullPath = ConfigurationManager.AppSettings["FilePath"] + FilePath;
return File.ReadAllText(FullPath);
}
Try to replace ContentType with application/octet-stream.
Related
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();
I have written the code for downloading a pdf file over http request.
public void downloadDocument(HttpServletRequest request,
HttpServletResponse response, #PathVariable("id") String docId)
throws Exception {
HttpSession session = request.getSession(true);
int accountId = (Integer) session.getAttribute("ownerAccountId");
Map<String, String> docMap = DbInteractor.getUploadedDocsByDocId(
Integer.valueOf(docId), accountId);
String docName = docMap.get("name");
String typeName = docMap.get("type");
String[] fileName = docName.split("\\.(?=[^\\.]+$)");
typeName= typeName.replace(" ", "");
if (typeName.equals("CCD/CCR")) {
typeName = "CCDorCCR";
}
String filename = typeName + docId + "." + fileName[1];
System.out.println(filename);
FileInputStream fileInputStream = new FileInputStream(
Constants.DOCUMENTS_PATH + filename);
response.setHeader("Expires", "0");
response.setHeader("Cache-Control",
"must-revalidate, post-check=0, pre-check=0");
response.setHeader("Content-disposition", "attachment; filename="
+ docName);
OutputStream os = response.getOutputStream();
IOUtils.copy(fileInputStream, os);
os.flush();
os.close();
}
But the file is getting automatically downloaded in chrome .Is there any way to force chrome to open this document in a viewer(or to ask for an open with dialog in chrome)
You are forcing the browser to download by sending "Content-Disposition: attachment".
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();
I have two files at the same location but the big one, when is about to finish download, gives an error (both in IE and Firefox).
I use the following code:
public static void DownloadZipFile (string filename, bool notifyMe)
{
HttpContext context = HttpContext.Current;
HttpServerUtility server = context.Server;
bool ok = false;
try
{
string file = string.Format ("~/contents/licensing/members/downloads/{0}", filename);
string server_file = server.MapPath (file);
HttpResponse response = context.Response;
//response.BufferOutput = false;
response.ContentType = "application/zip";
string value = string.Format ("attachment; filename={0}", filename);
response.AppendHeader ("Content-Disposition", value);
FileInfo f = new FileInfo (server_file);
long size = f.Length;
response.TransmitFile (server_file, 0, size);
response.Flush ();
ok = true;
response.End ();
}
catch (Exception ex)
{
Utilities.Log (ex);
}
finally
{
if (ok && notifyMe)
NotifyDownload (filename);
}
}
Any ideas?
Response.End() calls Response.Flush(). Try removing the Flush call.
The solution to this problem is to add the line:
response.AddHeader("Content-Length",size.ToString());
before the call to TransmitFile ().
The credits go to Jim Schubert (see his comment above).
I'm making a simple download service so a user can download all his images from out site.
To do that i just zip everything to the http stream.
However it seems everything is stored in memory, and the data isn't sent til zip file is complete and the output closed.
I want the service to start sending at once, and not use too much memory.
public void ProcessRequest(HttpContext context)
{
List<string> fileNames = GetFileNames();
context.Response.ContentType = "application/x-zip-compressed";
context.Response.AppendHeader("content-disposition", "attachment; filename=files.zip");
context.Response.ContentEncoding = Encoding.Default;
context.Response.Charset = "";
byte[] buffer = new byte[1024 * 8];
using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutput = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(context.Response.OutputStream))
{
foreach (string fileName in fileNames)
{
ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fileName);
zipOutput.PutNextEntry(zipEntry);
using (var fread = System.IO.File.OpenRead(fileName))
{
ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(fread, zipOutput, buffer);
}
}
zipOutput.Finish();
}
context.Response.Flush();
context.Response.End();
}
I can see the the worker process memory growing while it makes the file, and then releases the memory when its done sending. How do i do this without using too much memory?
Disable response buffering with context.Response.BufferOutput = false; and remove the Flush call from the end of your code.
use Response.BufferOutput = false; at start of ProcessRequest and flush response after each file.
FYI. This is working code to recursively add an entire tree of files, with streaming to browser:
string path = #"c:\files";
Response.Clear();
Response.ContentType = "application/zip";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", "hive.zip"));
Response.BufferOutput = false;
byte[] buffer = new byte[1024 * 1024];
using (ZipOutputStream zo = new ZipOutputStream(Response.OutputStream, 1024 * 1024)) {
zo.SetLevel(0);
DirectoryInfo di = new DirectoryInfo(path);
foreach (string file in Directory.GetFiles(di.FullName, "*.*", SearchOption.AllDirectories)) {
string folder = Path.GetDirectoryName(file);
if (folder.Length > di.FullName.Length) {
folder = folder.Substring(di.FullName.Length).Trim('\\') + #"\";
} else {
folder = string.Empty;
}
zo.PutNextEntry(new ZipEntry(folder + Path.GetFileName(file)));
using (FileStream fs = File.OpenRead(file)) {
ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(fs, zo, buffer);
}
zo.Flush();
Response.Flush();
}
zo.Finish();
}
Response.Flush();