Uploading bytearray via URLRequest - apache-flex

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.

Related

upload binary file using python requests

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)

How to send HTTP SOAP request to local Sonos device with NodeMCU?

How do I send a simple HTTP POST/GET SOAP request to my Sonos loudspeaker in Lua?
I have tried simple HTTP POST and GET requests with success, but I do not know where to start with SOAP requests.
Note: I am a newbie at this. I have never worked with a NodeMCU before nor have I programmed in Lua. I have experience in other languages though.
I know how to do it in C#, Java and PHP.
This works in Postman:
HTTP Headers:
SOAPAction:urn:schemas-upnp-org:service:AVTransport:1#Pause
Content-Type:text/xml; charset="utf-8"
Host:192.168.0.10:1400
BODY:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:Pause xmlns:u="urn:schemas-upnp-org:service:AVTransport:1"><InstanceID>0</InstanceID></u:Pause></s:Body></s:Envelope>
What I did is this and it does not work:
sendRequest("192.168.0.10")
function sendRequest(url)
print("Sending request to Sonos Playbar...")
sk = net.createConnection(net.TCP, 0)
sk:on("receive", function(sck, c) print(c) end )
sk:on("connection", function(sck, c)
print("\r\n\r\n\r\n")
-- HTTP 405: Method not allowed
-- sck:send("POST / HTTP/1.1\r\nHost: "..url..":1400\r\nConnection: keep-alive\r\nAccept: */*\r\n\r\n")
-- HTTP 500, UPnP 402: Invalid arguments
-- sck:send("POST /MediaRenderer/AVTransport/Control HTTP/1.1\r\nHost: "..url..":1400\r\nSOAPAction:urn:schemas-upnp-org:service:AVTransport:1#Pause\r\nConnection: keep-alive\r\n\r\nAccept: */*\r\n\r\n")
local content = nil;
content = "POST /MediaRenderer/AVTransport/Control\r\n"
content = content.."Host:192.168.0.10:1400\r\n"
content = content.."Content-Type:text/xml; charset=utf-8\r\n"
content = content.."SOAPAction:urn:schemas-upnp-org:service:AVTransport:1#Pause\r\n"
content = content.."\r\n"
-- SOAP Body
content = content.."<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\""
content = content.." s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
content = content.."<s:Body>"
content = content.."<u:Pause xmlns:u=\"urn:schemas-upnp-org:service:AVTransport:1\">"
content = content.."<InstanceID>0</InstanceID>"
content = content.."</u:Pause>"
content = content.."</s:Body>"
content = content.."</s:Envelope>"
-- SOAP Body End
print(content.."\r\n\r\n\r\n")
sck:send(content);
end)
sk:connect(1400, url)
end
I am getting this response of my Sonos player:
HTTP/1.1 500 Internal Server Error
CONTENT-LENGTH: 347
CONTENT-TYPE: text/xml; charset="utf-8"
EXT:
Server: Linux UPnP/1.0 Sonos/34.16-37101 (ZPS9)
Connection: close
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<s:Body>
<s:Fault>
<faultcode>s:Client</faultcode>
<faultstring>UPnPError</faultstring>
<detail>
<UPnPError xmlns="urn:schemas-upnp-org:control-1-0">
<errorCode>401</errorCode>
</UPnPError>
</detail>
</s:Fault>
</s:Body>
</s:Envelope>
What am I doing wrong? I copied and paste the text, basically. Maybe it is the order of headers? Maybe I am declaring the headers wrong or something?
I don't have a Sonos device to play with. Thus, this ain't a confirmed answer.
The string in your content variable is not a valid HTTP request. Sonos doesn't understand it as the error code 401 means "invalid action".
You need the separate HTTP headers with \r\n. An extra \r\n needs to be placed right before the HTTP body. Therefore, I'd expect that your content should be:
"POST http://192.168.0.10:1400/MediaRenderer/AVTransport/Control\r\n
SOAPAction:urn:schemas-upnp-org:service:AVTransport:1#Pause\r\n
Content-Type:text/xml; charset=\"utf-8\"\r\n
Host:192.168.0.10:1400\r\n\r\n
<s:Envelope xmlns:s=\"http://schemas.xml......"
Finally! I have it working! Below is the code to get it working:
sendRequest("192.168.0.10")
function sendRequest(url)
print("Sending request to Sonos Playbar...")
local content = nil;
content = "";
-- SOAP Body
content = content.."<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\""
content = content.." s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
content = content.."<s:Body>"
content = content.."<u:Pause xmlns:u=\"urn:schemas-upnp-org:service:AVTransport:1\">"
content = content.."<InstanceID>0</InstanceID>"
content = content.."</u:Pause>"
content = content.."</s:Body>"
content = content.."</s:Envelope>"
-- SOAP Body End
http.post("http://"..url..":1400/MediaRenderer/AVTransport/Control",
'Content-Type: text/xml; charset="utf-8"\r\n'..
'Host:'..url..':1400\r\n'..
'SOAPAction:urn:schemas-upnp-org:service:AVTransport:1#Pause\r\n',
content, function(code, data)
if(code < 0) then
print("HTTP request failed with code "..code)
else
print(code, data)
end
end)
end

File download with content-disposition set still shows "untitled file" in browser

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?

SOAP UI - Save HTTP request to a GZIP file

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.

HTTP multipart/form-data over Socket does not show the variables

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

Resources