I'm now already trying for hours, but somehow i don't figure out the problem. Here is a sample of my Request:
POST /test/upload/upload.php HTTP/1.0
Host: localhost
User-Agent: TestBrowser
Content-Type: multipart/form-data, boundary=635131229269 //edited
Content-Length: 94
--635131229269
Content-Disposition: form-data; name="testme"
contender
--635131229269--
It is sended over standard TCP/IP Socket to a PHP Server, but the $_POST['testme'] Value is always empty.
Does someone can see the bug in this Request? --> solved
There is a \r\n at the end which doesn't show in the Code here.
Thank you, that solved my first problem.
Maybe you can help my with my second aswell. As i had seen on your profile you are well with C# and there is my second problem. I'm trying to upload a file to my server and the filedata somehow does not requested properly, i think it's because of the encoding, but i'm not sure.
_content = _content
+ "--" + boundary + Environment.NewLine
+ "Content-Disposition: form-data; name=\"" + this._FileVarName + "\"; filename=\"" + Path.GetFileName(this._FilePath) + "\""
+ Environment.NewLine + "Content-Transfer-Encoding: application/octet-stream"
+ Environment.NewLine + Environment.NewLine;
mainContent = this.Combine(Encoding.UTF8.GetBytes(_content), StreamFile(this._FilePath));
private Byte[] StreamFile(string Path)
{
FileStream fs = new FileStream(Path, FileMode.Open, FileAccess.Read);
Byte[] ImageData = new byte[fs.Length];
fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length));
fs.Close();
return ImageData;
}
You have to specify the boundary (on line 4) without the leading dashes. Also I only count 92 bytes of payload.
Just to make this answer a bit more complete, there has to be a semicolon after "multipart/form-data" (see w3c forms spec)
Content-Type: multipart/form-data; boundary=635131229269
Related
I am using retool pltaform and Following Google's Upload file data documentation for multipart uploads I have constructed this request body. I'm using the result of Filedrop's base64 as the binary file in my request body.
the file is upload to the correct folder and get the right name and the right type but
I keep getting the "No preview available" when i open the image or PDF , i don't know which part of the request body is wrong...
Any support would be appreciated.
url and headers
--foo_bar_baz
Content-Type: application/json; charset=UTF-8
{'name': "{{filesDrop.files[0].name}}",'mimeType':'{{filesDrop.files[0].type}}','parents':['DRIVEID']}
--foo_bar_baz
Content-Type: {{filesDrop.files[0].type}}
Content-Transfer-Encoding: BASE64
{{filesDrop.value[0]}}//in base64 format
--foo_bar_baz--
let body = ""
let boundry = "--YOURBOUNDRY"
let rn = "\r\n"
// set file metadata
body += boundry + rn;
body += "Content-Type: application/json" + rn + rn;
body += "{\"name\":\"" + filesDrop.files[0].name + "\"}" + rn
// add actual file contents
body += boundry + rn;
body += "Content-Type: " + filesDrop.files[0].type + rn;
body += "Content-Transfer-Encoding: base64" + rn + rn;
body += filesDrop.value[0] + rn;
body += boundry + "--";
return body;
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?
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
I am trying to learn about how a HTTP client works in Java. I am trying to build my own client that will make a request to a web server for a php file.
Currently when I make the request the server gives me the following error:
HTTP/1.1 400 Bad Request
However, I am able to access the file from within a browser no problem. I don't know what I could be doing wrong but I can't figure it out. Below is the code for my HTTP Client class:
public class MyHttpClient {
MyHttpRequest request;
String host;
public MyHttpResponse execute(MyHttpRequest request) throws IOException {
//Creating the response object
MyHttpResponse response = new MyHttpResponse();
//Get web server host and port from request.
String host = request.getHost();
int port = request.getPort();
//Check 1: HOST AND PORT NAME CORRECT!
System.out.println("host: " + host + " port: " + String.valueOf(port));
//Get resource path on web server from requests.
String path = request.getPath();
//Check 2: ENSURE PATH IS CORRECT!
System.out.println("path: " + path);
//Open connection to the web server
Socket s = new Socket(host, port);
//Get Socket input stream and wrap it in Buffered Reader so it can be read line by line.
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(s.getInputStream()));
//Get Socket output stream and wrap it in a Buffered Writer so it can be written to line by line.
PrintWriter outToServer = new PrintWriter(s.getOutputStream(),true);
//Get request method
String method = request.getMethod();
//Check 3: ENSURE REQUEST IS CORRECT GET/POST!
System.out.println("Method: " + method);
//GET REQUEST
if(method.equalsIgnoreCase("GET")){
//Send request to server
outToServer.println("GET " + path + " HTTP/1.1 " + "\r\n");
String line = inFromServer.readLine();
System.out.println("Line: " + line);
}
//Returning the response
return response;
}
}
If anyone could shed some light on this issue I'd appreciate it very much! Thanks.
New Request To Server:
outToServer.print("GET " + path+ " HTTP/1.1" + "\r\n");
outToServer.print("Host: " + host + "\r\n");
outToServer.print("\r\n");
Response:
Method: GET
line: <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
line: <html><head>
line: <title>400 Bad Request</title>
line: </head><body>
line: <h1>Bad Request</h1>
line: <p>Your browser sent a request that this server could not understand.<br />
line: </p>
line: <hr>
line: <address>Apache Server at default.secureserver.net Port 80</address>
line: </body></html>
line: null
Do not use PrintWriter. You have to write ascii characters.
s.getOutputStream().write(("GET " + path + " HTTP/1.1\r\n\r\n").getBytes("ASCII"));
I think you need at least to add the Host header in the request.
Example taken from http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol
GET /index.html HTTP/1.1
Host: www.example.com
After the headers are complete you also need to transfer an extra \r\n so the server knows that the request is complete.
Do not use println but print. println adds another \n to every line causing the lines to be terminated with \r\n\n.
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.