How to convince chrome(browser) to show the download file dialog? - wcf

How to convince chrome(browser) to show the download file dialog while downloading a JSON content?
With the following headers chrome renders the JSON directly on the screen. Content-Type:application/json; charset=utf-8
Any ideas?

As it turns out, you only have to set the content disposition on the server end,
WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";
WebOperationContext.Current.OutgoingResponse.Headers.Add("Content-Disposition: attachment; filename=" + fileName + ".json");

Related

Pdf file uploaded using JMeter but the content is missing in that pdf file means file gets corrupted

I need to upload a pdf file through backend API using JMeter. So for that, I passed a multipart API request. To upload the file I am using BeanShell Preprocessor.
FileInputStream in = new FileInputStream("C:\\Users\\XYZ\\Downloads\\PT_003.pdf");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int i; (i = in.read(buffer)) != -1; ) {
bos.write(buffer, 0, i);
}
in.close();
byte[] binarydata = bos.toByteArray();
bos.close();
vars.put("binarydata", new String(binarydata));
Multipart Request Body :
--AaC07x
Content-Type: application/json; charset=utf-8
{
"token":"a6b8J000000055JQPU",
"flow":"Development"
}
--AaC07x
content-disposition: form-data; name="File"; filename="PT_003.pdf"
Content-Type: application/pdf
Content-Transfer-Encoding: bytecode
${binarydata}
--AaC07x--
Header Manager:-
Content-Type multipart/related;boundary="AaC07x"
File uploaded but content in that pdf file is missing means when I tried to open the uploaded pdf file it's blank/corrupted.
So can you please anyone help me to fix that issue??
It looks like your byte array to string conversion is the problem. Moreover as per JMeter 5.5 you cannot simply send a byte array using HTTP Request sampler as given you put everything into "Body Data" tab it will be treated as a String
Since JMeter 3.1 you should avoid using Beanshell, the recommended scripting language is Groovy
If you have problems coming up with a proper request definition you can just record it using HTTP(S) Test Script Recorder, just make sure that your PT_003.pdf is in JMeter's "bin" folder during both recording and replay

Posting PDF file with form-data: corrupted file?

I'm trying to upload a pdf file with form-data to a server. The upload works but the file gets corrupted for some reason (I can't open the uploaded version). Here's my code:
post_url = 'https://myposturl'
headers = {
'Content-Type':'multipart/form-data; charset=UTF-8; boundary=MyBoundary'
}
with open('./myfile.pdf', 'rb') as f:
body = f'--MyBoundary\r\nContent-Disposition: form-data; name="file"; filename="myfile.pdf"\r\nContent-Type: application/pdf\r\n\r\n{f.read()}\r\n--MyBoundary--\r\n'
res = s.post(post_url, headers = headers, data = body)
I thought it was coming from the \r\n, I tried a replace('\n', '\r\n') on the f.read() output but it didn't work.
Also, when using https://httpbin.org to check the POST request, I get \\\\r\\\\n for each new line in the pdf binary data. I'm wondering if this is normal, maybe that could help.
Thank you in advance for your suggestions.
With requests it can be done a bit easier.
import requests
post_url = 'https://myposturl'
files = {'file': open('./myfile.pdf', 'rb')}
r = requests.post(post_url, files=files)
More docs.
The reason you get corrupted file is probably because you're setting headers and body manually. requests usually sets theses things implicitly, so you should not break this concept and follow official guides.

How to write HttpWebRequest response to browser

I am trying to achieve this:
I have a website from where users buy files and then they see the download links.
Files are located on another location (some www.myfiles.com) the links are secure so the users dont see where are the files but actually the browser should start downloading the files as soon as they click.
user buy files, click on the link and i do this:
var filename = "SomeHighlySecureFile.mp3";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://myfiles.com/download.aspx?file=" + filename);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
context.Response.Buffer = true;
context.Response.Clear();
context.Response.AddHeader("content-disposition", "attachment; filename=" + fileinfo.Name);
context.Response.ContentType = "application/octet-stream";
I have no idea, what to do next? coz the "WriteFile" does not provide the options to write another stream?
Can anyone give me a clue how to do that?

Couldn't be downloaded IE

Using a streamwriter we are exporting an .csv file.
Response.ClearContent()
Response.ClearHeaders()
Response.ContentType = "application/vnd.ms-excel"
Response.AppendHeader("Content-disposition", "attachment; filename=Peuters.csv")
This worked until IE11 was released. The code never changed but in IE I am getting the message at the bottom ".csv couldn't be downloaded". Then when I click on Retry it downloads the complete page, html & js, not the export file.
Anyone found a solution for this?
Yes, already tried these steps: http://answers.microsoft.com/en-us/ie/forum/ie9-windows_7/couldnt-be-downloaded-appears-at-bottom-of-screen/ad51df58-bd7c-e011-9b4b-68b599b31bf5?msgId=61dd62bc-d592-4d54-8bd5-84a22ea59472
Didn't work.
Printscreen:
http://static.dyp.im/ufgMWUAXOb/1b257748b8489c192b53eae37623276c.png

405 - Method Not Allowed HttpWebRequest

I have a problem when trying to send a POST request. The sending method looks like this:
Public Sub SendXML(ByVal file As String)
Dim reader As New StreamReader(file)
Dim data As String = reader.ReadToEnd()
reader.Close()
Dim request As HttpWebRequest = WebRequest.Create("http://blah/Request")
request.Method = "POST"
System.Net.ServicePointManager.Expect100Continue = False
Dim bytes As Byte() = System.Text.Encoding.ASCII.GetBytes(data)
request.ContentLength = bytes.Length
Dim oStreamOut As Stream = request.GetRequestStream()
oStreamOut.Write(bytes, 0, bytes.Length)
oStreamOut.Close()
Dim response As HttpWebResponse = request.GetResponse()
End Sub
When running this I get the above error. Through Fiddler I can see that the request looks like:
POST http://blah/Request HTTP/1.1
Host: blah
Content-Length: 322
Proxy-Connection: Keep-Alive
<?xml version="1.0"?>
<Envelope>
<Header>
<UserID>uid</UserID>
<Password>pass</Password>
<SessionID />
<RequestType>GetDetails</RequestType>
<POSCompany>01</POSCompany>
<PackageType>DATA</PackageType>
<ActionType>READ</ActionType>
<SnoopUserID />
</Header>
<Body>
<MagicNumber>124</MagicNumber>
</Body>
</Envelope>
Now looking at this I suspected that it was due to the fact that the server does not accept POST messages. But some other reading suggests that the the URI http://blah/Request has been generated with a proxy and should be /Request so the line should read POST /Request HTTP/1.1
So what would be the common reason for this? And if it is a proxy problem, how is it sorted?
As asked below, I have created a new question for the more specific request. Changing absolute URI to relative in HTTP POST header
There is nothing wrong with the POST request, so the problem must lie elsewhere.
There are a number of other places along the way that could be causing trouble:
There could be a bad proxy between you and the server that is changing the HTTP method
The server could be malfunctioning or simply no support POST
My guess, however, is that the server is doing more than just looking at the HTTP method and is instead giving you a 405 error in response to the RPC call that your XML payload is wrapping.
Some RPC servers will (erroneously) use HTTP status codes like this to indicate that the requested method cannot be executed, or that something else is wrong with the request that is of a permissions and security nature.
If the server is slightly better behaved (and you are lucky), it should be returning additional information in the response body that might indicate where the 405 error is coming from.
Are you missing the Content-Type header required for a POST ?
Read here for details.
I assume it is mandatory.
Your POST appears to be completely invalid. POST data is supposed to be encoded (ie, as multipart/form-data) and use correct content-type (ie, application/x-www-form-urlencoded) with proper encoding and boundaries etc. You are just sending the server a lump of text and I'm not surprised it flips out.
I'm not 100% sure what VB is doing behind the scenes but this MSDN page suggests you need to set the content-type to a supported method and you probably need Content-Disposition: form-data in your headers as well. I found an example that does this and adds the MIME boundaries:
string FileData = "this is test file data\r\n"; // test data to send.
StringBuilder DataString = new StringBuilder();
DataString.Append(dataBoundary + "\r\n");
//This sends the viewstate info
DataString.Append("Content-Disposition: form-data; name=" + HiddenValue
+ "\r\n"
+ dataBoundary + "\r\n");
DataString.Append("Content-Disposition: form-data; name=" + "\"" +
"File1" +
"\"" +
"; filename=" + "\"" + "TestFile3.txt" + "\"" + "\r\n");
DataString.Append("Content-Type: text/plain\r\n\r\n");
DataString.Append(FileData);
DataString.Append(dataBoundary + "\r\n");
DataString.Append("Content-Disposition: form-data; name=" + "\"" +
"Submit1" +
"\"" + "\r\n\r\n" + "Upload\r\n" + dataBoundary + "--\r\n");
That example emulates a file field upload.
For a simpler version you can use request.ContentType = "application/x-www-form-urlencoded" with URL-encoded data like: Dim postData As String = "myURL=http%3A%2F%2Fexample.com%2Findex.php". Note that the format is key=value and the data must be URL-encoded first.
I'm not sure what exactly you need though because a lot depends on what the remote server actually expects for the form and field names. It also depends wether the server is actually following the relevant HTML standards and RFCs. Do you have a working HTML form to use as a guide for what the server expects?