I want to get a file (image or video) from an
<input type='file' id='file_i'/>
// Not this <input type='submit'/>
Using an XMLHttpRequest like this
function img() {
var fd = new FormData();
fd.append('file', document.getElementById("file_i").files[0]);
var req;
if (window.ActiveXObject) {
req=new ActiveXObject();
} else {
req=new XMLHttpRequest();
}
req.open("post", "Image", true);
req.send(fd);
}
for example.
Then in the servlet doing this:
new FileInputStream(new File(request.getParameter("file")))
How can I retrieve that file?
Thanks in advance.
I fixed it. Here it is:
JAVASCRIPT
var fd = new FormData();
fd.append('file', document.getElementById("file_i").files[0]);
var req;
if (window.ActiveXObject) {
req=new ActiveXObject();
} else {
req=new XMLHttpRequest();
}
req.open("post", "Image", true);
req.send(fd);
JAVA
#MultipartConfig
public class addImage extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
Part filePart = request.getPart("file");
InputStream fileContent = filePart.getInputStream();
}
}
XML
<servlet>
<servlet-name>Add Image</servlet-name>
<servlet-class>servlets.addImage</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Add Image</servlet-name>
<url-pattern>/Image</url-pattern>
</servlet-mapping>
I think you miss some points.
It seems in your JavaScript code, that you just create the request. But you didn't respond to results.
req.addEventListener("load", reqListener);
You should define reqListener like that:
function reqListener () {
// Here try to handle the response text, using "this.responseText"
console.log(this.responseText);
}
See the full info here:
Using XMLHttpRequest
Also in your Java code, you just stated that you created a file stream.
You should read from this input stream into the request's output stream. Also you should set the header Content-Type: put_your_mime_type_here, For example: Content-Type: application/json, if your file is a json file, Content-Type: image/png, if your file is a PNG image.
See an example here: Example for making a file download URL in Java
Related
I want to be able to paste an image taken via the print screen button in a textarea and upload it to my server.
I am using onpaste and it seems to work, I can get a hold of a file object but whenever I try to send it it's empty.
onpaste(event) {
if (event.clipboardData.files.length) {
let file = event.clipboardData.files[0];
var oReq = new XMLHttpRequest();
var data = new FormData();
data.append("file", file);
data.append("csrf", CSRF_TOKEN);
oReq.open("POST", exports.url("/file"));
oReq.setRequestHeader("Accept", "application/json");
oReq.send(data);
}
}
I observe the network tab in my dev tools and a request is properly being sent with all of the information about the file except there is no contents
Request payload:
------WebKitFormBoundaryWggS2BbKcZV6v4tn
Content-Disposition: form-data; name="file"; filename="image.png"
Content-Type: image/png
------WebKitFormBoundaryWggS2BbKcZV6v4tn
Content-Disposition: form-data; name="csrf"
58718518696317230756900774635415
------WebKitFormBoundaryWggS2BbKcZV6v4tn--
In this case the file you access via event.clipboardData.files[0]; is really just a handle to the file, it doesn't contain the actual file data. To access this you must use a FileReader per the FileAPI documentation.
There are four different ways to read this data through the FileReader:
void readAsArrayBuffer(Blob blob);
void readAsBinaryString(Blob blob);
void readAsText(Blob blob, optional DOMString label);
void readAsDataURL(Blob blob);
See below an example which you can modify to fit your needs.
function onPaste(event) {
if (event.clipboardData.files.length) {
let file = event.clipboardData.files[0];
var oReq = new XMLHttpRequest();
var data = new FormData();
data.append("csrf", "TOKEN");
oReq.open("POST", "/file");
oReq.setRequestHeader("Accept", "application/json");
/* Create a new FileReader. */
var fileReader = new FileReader();
fileReader.onload = function(event) {
/* Once the file has finished loading, run the following: */
data.append("file", this.result);
oReq.send(data);
};
/* Tell the file reader to asynchronously load the files contents. */
fileReader.readAsDataURL(file);
}
}
<textarea onpaste="onPaste(event)" ></textarea>
I am calling API to return a JSON with all needed objects (notes):
$( document ).ready(function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
var response = xhr.responseText;
//do stuff with response
}
xhr.open('GET', 'http://mydomain:8080/notes/all', true);
xhr.send(null);
});
HTTP request:
#RequestMapping(value = {"/all"}, method = RequestMethod.GET, produces = "application/json")
public #ResponseBody List<Note> getAllNotes() {
return noteService.getAllNotes();
}
When I run locally on Mac, everything works. My Response header has Content-Type: application/java, and Request accepts it.
However, when I upload my .war to Ubuntu 16.04 server, Request header's Content-Type changes to txt/html, and I get
404 Page Not Found
.
I am using tomcat8.5.5 on both machines.
How do I specify/change the Request Header Content-Type?
Images of headers:
running on remote
and local
I noticed that I had <script src="noteAPI.js"></script> declaration in BOTH index.html and notes.html. I have removed this declaration from index.html and it worked!
My current code:
Javascript
function pushFunc() {
mediaRecorder.requestData();
console.log(mediaRecorder.state);
mediaRecorder.ondataavailable = function (e) {
console.log("data size: ", e.data.size);
var encodeData = new Blob([e.data], { type: 'video/mp4' });
postBlobData(encodeData);
}
}
function postBlobData(blob) {
var formData = new FormData();
formData.append("blobContent", blob);
var request = new XMLHttpRequest();
request.open("POST", "/Device/Upload");
request.send(formData);
}
ASP.NET
**File: DeviceController.cs**
[HttpPost]
public string Upload(HttpPostedFileBase blobContent)
{
...
// return View();
}
The Java script code gets the blob from Media recorder and tries to post it down to the Controller.
Am i grabbing and posting blobs the way i should?
Should HttpPostedFileBase be used to receive the post request on the server side?
Fiddler Screenshot#1
Fiddler Screenshot#2
Fiddler Screenshot#3
I am using the following snippet to send a wav file as a blob to the server which is written in PHP:
function upload(blob) {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/upload.php', true);
xhr.onload = function (e) {
var result = e.target.result;
};
xhr.send(blob);
}
I am confused as to how I should handle the POST data on the server.
What you're looking for is php://input:
$fp = fopen("php://input", "r");
$wav_file = stream_get_contents($fp);
Note that I'm assuming blob in your example is an actual Blob, or ArrayBuffer, or File, and not just a bunch of text whose UTF8 interpretation is also a valid WAVE file.
<input type="file" id="uploadfile" name="uploadfile" />
<input type="button" value="upload" onclick="upload()" />
<script>
var client = new XMLHttpRequest();
function upload()
{
var file = document.getElementById("uploadfile");
/* Create a FormData instance */
var formData = new FormData();
/* Add the file */
formData.append("upload", file.files[0]);
client.open("post", "/upload", true);
client.setRequestHeader("Content-Type", "multipart/form-data");
client.send(formData); /* Send to server */
}
/* Check the response status */
client.onreadystatechange = function()
{
if (client.readyState == 4 && client.status == 200)
{
alert(client.statusText);
}
}
</script>
Trying to Upload some Images stored in Filesystem of Google Chrome.
But Im not able to upload the Image. Any Idea how to do it?
The Server receives an empty array. The Code of posttest.php is just print_r($_POST)
var xhr = new XMLHttpRequest();
xhr.open('POST', '/posttest.php', true);
xhr.onload = function(e) {
if (this.status == 200) {
console.log(this.responseText);
}
};
window.resolveLocalFileSystemURL(image, function(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
var formData = new FormData();
formData.append('image', this.result);
xhr.send(formData);
};
reader.readAsText(file);
});
});
this is the Javascript function that worked for me in chrome
function upload(filename) {
var xhr = new XMLHttpRequest();
xhr.open("post", "upload.php", true);
window.resolveLocalFileSystemURL = window.resolveLocalFileSystemURL || window.webkitResolveLocalFileSystemURL;
filename = 'filesystem:http://localhost/temporary/' + filename;
window.resolveLocalFileSystemURL(filename, function(fileEntry) {
fileEntry.file(function(file) {
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("X-File-Type", file.type);
xhr.send(file);
});
});
}
Now most people on the skip the upload.php taking it for granted. But it is very important and so I paste it here:
<?php
// I had to figure out what is getting passed using var_dump($_SERVER)
$fn = (isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : false);
if ($fn) {
// AJAX call
file_put_contents(
'uploads/' . $fn,
file_get_contents('php://input')
);
echo "$fn uploaded";
exit();
}
?>
Hope this helps someone, I wasted an entire day to figure this out !
First of all, your comment isn't exactly correct, the PHP code shouldn't even be receiving a blob. It's just receiving text, because you read the file as text, while png images (and almost all image types) aren't supposed to be text, they're supposed to be binary. And Blobs themselves are perfect for storing binary data, so you don't even need to use a FileReader, you can just send the Blob itself through XMLHttpRequest!
Here is how the revised fileEntry.file callback function should look:
fileEntry.file(function(file) {
xhr.send(file);
});
It's that simple! No need to read the Blob. However, you need to do some more stuff on the
PHP side now. This code will write the contents of the uploaded image to disk, then create an <img> element that allows you to view it. Here's how the PHP /posttest.php should look for that:
<?php
$rhand=fopen('php://input','r');
$cont=fread($rhand,filesize('php://input'));
fclose($rhand);
$whand=fopen('./uploaded.png','w');
fwrite($whand,$cont);
fclose($whand);
?>
<img src="uploaded.png">
It should be pretty clear what that does if you know that php://input is where php will get input from a post request if it doesn't have a MIME type that allows it to easily put it into $_POST (For example, when you have have a request with MIME type application/x-www-form-urlencoded, PHP recognizes it and is able to parse the POST contents into $_POST, but with a Blob, it doesn't, so it just outputs it out of php://input)
Please note that none of this is tested, please put a comment if it doesn't work and I'll try to fix it!
Having encountered the same challenge myself, I was able to come up with a very sleek solution. The key is to create a new Blob, from the file object returned by the fileEntry.
window.resolveLocalFileSystemURL = window.resolveLocalFileSystemURL || window.webkitResolveLocalFileSystemURL;
window.resolveLocalFileSystemURL(image, function (fileEntry) {
fileEntry.file(function (file) {
var formData = new FormData();
var tempBlob=new Blob([this.result], {type:this.result.type});
formData.append('image', tempBlob);
});
});