You need to sign in to do that
Don't have an account?
VarunC
File Upload using HttpRequest not working
Hi
I'm trying to upload Files from Visualforce page and APEX, via HttpRequest like this:
Http h = new Http(); HttpRequest req = new HttpRequest(); req.setMethod('POST'); req.setEndpoint(ENDPOINT_URL); req.setBody('file='+EncodingUtil.urlEncode(att.Name, 'UTF-8').replace('+','%20')); req.setHeader('Content-Type','application/x-www-form-urlencoded'); OAuth oa = new OAuth(); oa.sign(req); /* random string */ String boundary = 'R50hrfBj5JYyfR3vF3wR96GPCC9Fd2q2pVMERvEaOE3D8LZTgLLbRpNwXek3'; req.setHeader('Content-Type','multipart/form-data; boundary='+boundary); String bd='--'+ boundary +'\r\n'; bd+='Content-Disposition: form-data; name=file; filename='+ att.Name + '\r\n'; bd+='Content-type: application/octet-stream\r\n'; bd+='\r\n'; bd+= att.Body.toString(); bd+='\r\n'; bd+='--'+ boundary +'--'; req.setBody(bd); HttpResponse res = null; res = h.send(req);
VF page code is:
<span class="normal" style="font-weight:bold;">Select file:
<apex:inputfile styleClass="normal" id="file" size="25" value="{!att.Body}" fileName="{!att.Name}" />
</span>
<apex:commandButton value=" Upload " action="{!UploadFile}" />
This code is working fine for text files, but when I upload an Image or pdf file the upload gets corrupted. Can anyone tell mw what's wrong with this code? plz ...
I hypothesize that your corruption might be due to carriage/newline handling, or it might be because of utf8 encoding (remember, strings are textual, and so are subject to utf8 processing when output). I would add a "Content-Encoding: base64" to the body, and use EncodingUtil.Base64Encode(att.Body) to convert the binary data to Base64 encoding. Most processing languages are "intelligent" enough to change the encoding back into an octet stream when it receives a content encoding header. Other than that, I would review your use of carriage returns/new lines. It might be that your server is interpreting them differently than you expect (not all servers tolerate \r\n / \n\r correctly, so using \r is preferred). Also, you could try adding a Content-Length header so that a trailing newline character won't trip things up (assuming the recipient server can count!).
There's no way to send binary data over the HttpRequest object, you see corrupt due to random binary data not being a valid utf-8 text stream
wow .. didn't knew that .. :( ... is there any way aroun this? Can I do OAuth authentication and request sending to upload using VF page only and javascript ? ....
Hi.
Try this solution. Valid for servers that only support binary content and for servers that support base64 encoding.
http://salesforceafondo.wordpress.com/2013/01/08/post-multipartform-data-out-of-salesforce-com-with-...
Hope this helps.
José Luis Almazán.