Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Assuming that your Java code is using <a href="http://hc.apache.org/" rel="nofollow">Apache HttpComponents</a> (what you really should have said then), your code, when augmented with</p> <pre><code>URI aWebImageUrl2 = new URI("http://localhost:1337/"); File imgPath = new File("…/face.png"); final String aImgCaption = "face"; // … HttpClient httpClient = new DefaultHttpClient(); httpClient.execute(post); </code></pre> <p>submits the following example HTTP request (as tested with <code>nc -lp 1337</code>, see <a href="http://netcat.sourceforge.net/" rel="nofollow">GNU Netcat</a>):</p> <pre><code>POST / HTTP/1.1 Content-Length: 990 Content-Type: multipart/form-data; boundary=oQ-4zTK_UL007ymPgBL2VYESjvFwy4cN8C-F Host: localhost:1337 Connection: Keep-Alive User-Agent: Apache-HttpClient/4.1.2 (java 1.5) --oQ-4zTK_UL007ymPgBL2VYESjvFwy4cN8C-F Content-Disposition: form-data; name="picture"; filename="face.png" Content-Type: application/octet-stream �PNG[…] </code></pre> <p>The simplest solution to do something like this in HTML is, of course, to use a <a href="http://www.w3.org/TR/html401/interact/forms.html#h-17.3" rel="nofollow"><code>FORM</code> element</a> and no or minimal client-side scripting:</p> <pre><code>&lt;form action="http://service.example/" method="POST" enctype="multipart/form-data"&gt; &lt;input type="file" name="picture"&gt; &lt;input type="submit"&gt; &lt;/form&gt; </code></pre> <p>which submits (either when submitted with the submit button or the form object's <code>submit()</code> method) the following example request:</p> <pre><code>POST / HTTP/1.1 Host: localhost:1337 Connection: keep-alive Content-Length: 886 Cache-Control: max-age=0 Origin: http://localhost User-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1 Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryhC26St5JdG0WUaCi Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Referer: http://localhost/scripts/test/XMLHTTP/file.html Accept-Encoding: gzip,deflate,sdch Accept-Language: de-CH,de;q=0.8,en-US;q=0.6,en;q=0.4 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 ------WebKitFormBoundaryhC26St5JdG0WUaCi Content-Disposition: form-data; name="picture"; filename="face.png" Content-Type: image/png �PNG[…] </code></pre> <p>But since you have asked explicitly about a "javascript" solution (there really is <a href="http://PointedEars.de/es-matrix" rel="nofollow">no such programming language</a>), I presume that you want to have more client-side control over the submit process. In that case, you can use the <a href="http://www.w3.org/TR/FileAPI/" rel="nofollow">W3C File API</a> and <a href="https://developer.mozilla.org/en/docs/Ajax" rel="nofollow">XMLHttpRequest</a> or <a href="http://www.w3.org/TR/XMLHttpRequest2/" rel="nofollow">XMLHttpRequest2</a> APIs as provided by recent browsers (<em>not</em> the programming languages):</p> <pre><code>&lt;script type="text/javascript"&gt; function isHostMethod(obj, property) { if (!obj) { return false; } var t = typeof obj[property]; return (/\bunknown\b/i.test(t) || /\b(object|function)\b/i.test(t) &amp;&amp; obj[property]); } var global = this; function handleSubmit(f) { if (isHostMethod(global, "XMLHttpRequest")) { try { var input = f.elements["myfile"]; var file = input.files[0]; var x = new XMLHttpRequest(); x.open("POST", f.action, false); // ¹ try { var formData = new FormData(); formData.append("picture", file); x.send(formData); return false; } catch (eFormData) { try { var reader = new FileReader(); reader.onload = function (evt) { var boundary = "o" + Math.random(); x.setRequestHeader( "Content-Type", "multipart/form-data; boundary=" + boundary); x.send( "--" + boundary + "\r\n" + 'Content-Disposition: form-data; name="picture"; filename="' + file.name + '"\r\n' + 'Content-Type: application/octet-stream\r\n\r\n' + evt.target.result + '\r\n--' + boundary + '--\r\n'); }; reader.readAsBinaryString(file); return false; } catch (eFileReader) { } } } catch (eFileOrXHR) { } } return true; } &lt;/script&gt; &lt;form action="http://service.example/" method="POST" enctype="multipart/form-data" onsubmit="return handleSubmit(this)"&gt; &lt;input type="file" name="myfile"&gt; &lt;input type="submit"&gt; &lt;/form&gt; </code></pre> <p>This approach tries to use the XMLHttpRequest API. If that fails, the function returns <code>true</code>, so <code>true</code> is returned to the event handler (see the attribute value), and the form is submitted the usual way (the latter might not work with your Web service; test before use by disabling script support).</p> <p>If XMLHttpRequest can be used, it is "tested"² if the file input has a <code>files</code> property and the object referred to by that has a <code>0</code> property (referring to the first selected <code>File</code> for that form control, if supported).</p> <p>If yes, the XMLHttpRequest2 API is tried, which <code>send()</code> method <a href="http://www.w3.org/TR/XMLHttpRequest2/#the-send-method" rel="nofollow">can take a reference to a <code>FormData</code></a> and do all the multi-part magic by itself. If the XMLHttpRequest2 API is not supported (which should throw an exception), the File API's <code>FileReader</code> is tried, which can read the contents of a <code>File</code> as binary string (<code>readAsBinaryString()</code>); if that is successful (<code>onload</code>), the request is prepared and submitted. If one of those approaches seemingly worked, the form is not submitted (<code>return false</code>).</p> <p>Example request submitted with this code using the FormData API:</p> <pre><code>POST / HTTP/1.1 Host: localhost:1337 Connection: keep-alive Content-Length: 887 Origin: http://localhost User-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1 Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryLIXsjWnCpVbD8FVA Accept: */* Referer: http://localhost/scripts/test/XMLHTTP/file.html Accept-Encoding: gzip,deflate,sdch Accept-Language: de-CH,de;q=0.8,en-US;q=0.6,en;q=0.4 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 ------WebKitFormBoundaryLIXsjWnCpVbD8FVA Content-Disposition: form-data; name="picture"; filename="face.png" Content-Type: image/png �PNG[…] </code></pre> <p>The example request looks slightly different when the FileReader API was used instead (just as proof of concept):</p> <pre><code>POST / HTTP/1.1 Host: localhost:1337 Connection: keep-alive Content-Length: 1146 Origin: http://localhost User-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1 Content-Type: multipart/form-data; boundary=o0.9578036249149591 Accept: */* Referer: http://localhost/scripts/test/XMLHTTP/file.html Accept-Encoding: gzip,deflate,sdch Accept-Language: de-CH,de;q=0.8,en-US;q=0.6,en;q=0.4 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 --o0.9578036249149591 Content-Disposition: form-data; name="picture"; filename="face.png" Content-Type: application/octet-stream PNG[…] </code></pre> <p>Notice that the XMLHttpRequest2, FormData and File API are having only <em>Working Draft</em> status and so are still in flux. Also, this approach works if the resource submitted from and the resource submitted to are using the same protocol, domain, and port number; you may have to deal with and <a href="http://en.wikipedia.org/wiki/XMLHttpRequest#Cross-domain_requests" rel="nofollow">work around the Same Origin Policy</a>. Add feature tests and more exception handling as necessary.</p> <p>Also notice that the request made using <code>FileReader</code> is larger with the same file and misses the leading character, as indicated in the question referred to by Frits van Campen. This may be due to a (WebKit) bug, and you may want to remove this alternative then; suffice it for me to say that the <code>readAsBinaryString()</code> method is <em>deprecated</em> already in the File API Working Draft in favor of <code>readAsArrayBuffer()</code> which should use <a href="http://www.khronos.org/registry/typedarray/specs/latest/" rel="nofollow">Typed Arrays</a>.</p> <p>See also <a href="https://developer.mozilla.org/en/Using_files_from_web_applications" rel="nofollow">"Using files from web applications"</a>.</p> <p>¹ Use <code>true</code> for asynchronous handling; this avoids UI blocking, but requires you to do processing in the event listener, and you will always have to cancel form submission (even if XHR was unsuccessful).</p> <p>² If the property access is not possible, an exception will be thrown. If you prefer a real test, implement (additional) feature-testing (instead), and be aware that not everything can be safely feature-tested.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload