I'm writing a controller method in ASP.NET WebAPI to download a file. Here's the part where I set the headers and content:
result.Content = new StreamContent(new MemoryStream(csvResult));
result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/csv");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = fileName;
result.Content.Headers.ContentLength = csvResult.Length;
The file is being downloaded, but the browser always shows it as "untitled file". Fiddler shows the request coming back with the correct headers:
Content-Disposition: attachment; filename=Report2015-9_createtest3.csv
Content-Length: 1477
Content-Type: text/csv
I've tried it with the content-type as "application/octet-stream" and "text/plain" and those don't work any better either. Any idea what's going on?
Related
I am uploading a file using requests library below is the code:
files = {'file': open(full_file_name, 'rb')}
headers = {"content-type": 'application/x-www-form-urlencoded'}
final_resp = requests.put(loc, files=files, headers=headers)
The problem is some extra contents have been added to the file's start and end point.
The contents added to the start point is:
--b16010ae7646a031a5adc64ac0661e72
Content-Disposition: form-data; name="file"; filename="1016064585-65769268.csv"
The contents added to the endpoint is:
--b16010ae7646a031a5adc64ac0661e72--
But when the same file is uploaded through the postman these problems are not arising.
here is the screenshot of the postman .
The header of the postman is:
application/x-www-form-urlencoded
it may because you use multipart/form to upload file.try use data like code below
data = open(localFilePath, 'rb').read()
headers = {
"Content-Type":"application/binary",
}
upload = requests.put(uploadUrl,data=data,headers=headers)
I m using Soap UI free version for some rest mocking.
I need to persist my HTTP POST request (request received already compressed gzip) to a gzip file.
I have tried different ways to do that, however after to execute the code, when I try to decompress manually the file I have the following error: "The archive is either in unknown format or damaged".
The HTTP POST request has the following header:
Host : 127.0.0.1:8091
Content-Length : 636
User-Agent : Java/1.7.0_07
Connection : keep-alive
Content-Type : application/octet-stream
Accept : text/plain, application/json, application/*+json, */*
Pragma : no-cache
Cache-Control : no-cache
Below the solutions that I have tried:
Solution#1:
byte[] buffer = new byte[1024];
byte[] data = mockRequest.getRequestContent().getBytes();
def path="myfile.gz";
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path));
bos.write(data);
bos.flush();
bos.close();
Solution#2
byte[] buffer = new byte[1024];
byte[] data = mockRequest.getRawRequestData();
def path="myfile.gz";
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path));
bos.write(data);
bos.flush();
bos.close();
Can someone please help and let me know why I cannot decompress the gzip file and how I can do that?
Thanks,
This is Groovy, so you don't need all this Java clutter.
Here's some code that might work:
new File( path) << mockRequest.rawRequestData
EDIT
Ok, based on your comments, for zip files to be copied correctly, you probably need something a little different:
import java.nio.file.*
Files.copy(new ByteArrayInputStream(mockRequest.requestContent.bytes),
Paths.get( 'destination.zip' ) )
Tested this with an actual zip file's byte[] as source and it worked. If it does not work for you, then the byte array you're getting from requestContent.bytes just isn't a zip file.
I wrote a simple asp.net page that simulates file download response. I added the following lines to adjust response:
Response.AddHeader("ETag", "\"" + _EncodedData + "\"");
Response.AddHeader("Last-Modified", lastUpdateTiemStamp);
Response.AddHeader("Accept-Ranges", "bytes");
//Set the ContentType
Response.ContentType = "application/octet-stream";
//Add the file name and attachment,
//which will force the open/cancel/save dialog to show, to the header
Response.AddHeader("Content-Disposition", "attachment;filename=" + dItem.FileName);
//Add the file size into the response header
Response.AddHeader("Content-Length", (endByte - startBytes).ToString());
Response.AddHeader("Connection", "Keep-Alive");
My problem is that Accept-ranges doesn't apear in the response header, but when I change Accept-Ranges to Accept-Ranges1 this header(Accept-Ranges1) will receive a response header.
This problem only occurs when I am debugging the project in Visual Studio. When I am on IIS everything is ok
We have a web page that is grabs a series of strings from a url, finds some pdfs associated with those strings, zips them up using DotNetZip, and returns them to the user. The page that does this is very simple - here's the Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
string[] fileNames = Request.QueryString["requests"].Split(',');
Response.Clear();
Response.ClearHeaders();
Response.ContentType = "application/zip";
string archiveName = String.Format("MsdsRequest-{0}.zip", DateTime.Now.ToString("yyyy-mm-dd-HHmmss"));
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + archiveName + "\"");
using (ZipFile zip = new ZipFile())
{
foreach (string fileName in fileNames)
{
zip.AddFile(String.Format(SiteSettings.PdfPath + "{0}.pdf", msdsFileName), "");
}
zip.Save(Response.OutputStream);
}
Response.Flush();
}
(Before you ask, it would be fine if someone put other values in this url...these are not secure files.)
This works fine on my development box. However, when testing on our QA system, it downloads the zipped file, but it is corrupt. No error is thrown, and nothing is logged in the event log.
It may be possible for me to find a way to interactively debug on the QA environment, but since nothing is actually failing by throwing an error (such as if the dll wasn't found, etc.), and it's successfully generating a non-empty (but corrupt) zip file, I'm thinking I'm not going to discover much by stepping through it.
Is it possible that this is some kind of issue where the web server is "helping" me by "fixing" the file in some way?
I looked at the http response headers where it was working on my local box and not working on the qa box, but while they were slightly different I didn't see any smoking gun.
As an other idea I rejected, the content length occured to me as a possibility since if the content length value was too small I guess that would make it corrupt...but I'm not clear why that would happen and I don't think that's exactly it since if I try to zip and download 1 file I get a small zip...while downloading several files gives me a much larger zip. So that, combined with the fact that no errors are being logged, makes me think that the zip utility is correctly finding and compressing files and the problem is elsewhere.
Here are the headers, to be complete.
The response header on my development machine (working)
HTTP/1.1 200 OK
Date: Wed, 02 Jan 2013 21:59:31 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Content-Disposition: attachment; filename="MsdsRequest-2013-59-02-165931.zip"
Transfer-Encoding: chunked
Cache-Control: private
Content-Type: application/zip
The response header on the qa machine (not working)
HTTP/1.1 200 OK
Date: Wed, 02 Jan 2013 21:54:37 GMT
Server: Microsoft-IIS/6.0
P3P: CP="NON DSP LAW CUR TAI HIS OUR LEG"
SVR: 06
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Content-Disposition: attachment; filename="MsdsRequest-2013-54-02-165437.zip"
Cache-Control: private
Content-Type: application/zip
Set-Cookie: (cookie junk removed);expires=Wed, 02-Jan-2013 21:56:37 GMT;path=/;httponly
Content-Length: 16969
Not sure how to approach this since nothing is claiming a failure. I feel like this could be a web server configuration issue (since I don't have any better ideas), but am not sure where to look. Is there a tact I can take?
As it is you have miss to give an End() to the page right after the Flush() as:
...
zip.Save(Response.OutputStream);
}
Response.Flush();
Response.End();
}
But this is not the correct way, to use a page to send a zip file, probably IIS also gZip the page and this may cause also issues. The correct way is to use a handler and also avoid extra gZip compression for that handler by ether configure the IIS, ether if you make the gZip compression avoid it for that one.
a handler with a name for example download.ashx for your case will be as:
public void ProcessRequest(HttpContext context)
{
string[] fileNames = Request.QueryString["requests"].Split(',');
context.Response.ContentType = "application/zip";
string archiveName = String.Format("MsdsRequest-{0}.zip", DateTime.Now.ToString("yyyy-mm-dd-HHmmss"));
context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + archiveName + "\"");
// render direct
context.Response.BufferOutput = false;
using (ZipFile zip = new ZipFile())
{
foreach (string fileName in fileNames)
{
zip.AddFile(String.Format(SiteSettings.PdfPath + "{0}.pdf", msdsFileName), "");
}
zip.Save(context.Response.OutputStream);
}
}
I'm trying to upload a bytearray, but am struggling to make the content-type go as image/png (it always goes as application/octet-stream no matter what I do.).
I've checked the request with Charles Proxy, and can confirm that it indeed always goes as application/octet-stream.
My code is:
protected function onObjectLoaded(event:Event):void
{
var byteArray:ByteArray = new ByteArray();
var fileName:String = fileReference.name;
var uploadPath:String = serviceURL;
var parameters:Object = new Object();
parameters.key = serviceKey;
fileReference.data.readBytes(byteArray,0,fileReference.data.length);
var urlRequest:URLRequest = new URLRequest();
urlRequest.url = uploadPath;
urlRequest.contentType = 'multipart/form-data; boundary=' + UploadPostHelper.getBoundary();
urlRequest.method = URLRequestMethod.POST;
urlRequest.data = UploadPostHelper.getPostData(fileName, byteArray, "fileupload", parameters);
urlRequest.requestHeaders.push( new URLRequestHeader( 'Content-type', 'image/png' ) );
var urlLoader:URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
/*urlLoader.addEventListener(Event.COMPLETE, onComplete);
urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onError);
urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);*/
urlLoader.addEventListener(Event.COMPLETE, processResults);
urlLoader.load(urlRequest);
}
As you can see, I;m passing the content type as "multipart/form-data". I've tried passing it as image/png, which made the request itself go as image/png as expected, however, the image itself still goes as application/octet-stream.
Here's what my request looks like right now:
--rojpkvwesrtjvrgjbwtadelavgcmxjot Content-Disposition: form-data;
name="key"
WZL0NXBE6dcb9af80668bb96b86fa72f5595422c
--rojpkvwesrtjvrgjbwtadelavgcmxjot Content-Disposition: form-data;
name="Filename"
Canada.png
--rojpkvwesrtjvrgjbwtadelavgcmxjot Content-Disposition: form-data;
name="fileupload"; filename="Canada.png" Content-Type:
application/octet-stream
‰PNG -- Loads of image information here as a bytearray
As you can see Canada.png is being passed in as application/octet-stream. I've fiddled with the request, and have manually made it work, as to what my server expected to receive, which is exactly the same as above, but where it says:
Canada.png
--rojpkvwesrtjvrgjbwtadelavgcmxjot Content-Disposition: form-data;
name="fileupload"; filename="Canada.png" Content-Type:
application/octet-stream
It should say:
Canada.png
--rojpkvwesrtjvrgjbwtadelavgcmxjot Content-Disposition: form-data;
name="fileupload"; filename="Canada.png" Content-Type:
image/png
My question is how to change this, so the bytearray itself gets passed in as image/png instead of octet-stream
This image is being upload from the client side, and being passed as a FileReference, which I then invoke load(), and then get it's "data" attribute, which is where the bytearray is.
Any help here would be much appreciated, as I've been struggling with this for a few hours, but can't seem to be able to change the mime type of the bytearray.
Thanks in advance,
The content-type in your request is set inside UploadPostHelper class. As far as I can tell it is hard-coded as application/octet-stream. You can just change it to image/png if you only going to upload png images. Or you can use another url request wrapper for uploading files that allows you to specify content-type of a file. For example MultipartURLLoader.