Javascript file upload not working in Chrome
I have implemented the following JS code to upload a file. In IE it works fine, but in chrome I get an empty file on the server side. I looked at the request data using Fiddler and found that the request doesn't contain the file data in Chrome (in IE it does). It looks like this:
----WebkitFormBoundary4kjth5kjt54h
Content-Disposition: form-data; name="C:fakepathfile.txt"; filename=""
Content-Type: application/octet-stream
----WebkitFormBoundary4kjth5kjt54h--
And in IE it looks like:
----------------7dd435hb8d7gs34
Content-Disposition: form-data; name="C:fakepathfile.txt"; filename="file.txt"
Content-Type: text/plain
The file data bla bla bla
----------------7dd435hb8d7gs34--
So there must be a problem on the client side, but I can't figure out what it is.
This code is being activated when the user clicks a button.
Please don't suggest creating a regular HTML <form>
tag, because my case doesn't make it possible. It has to be done using javascript.
var form = document.createElement("FORM");
form.method = "post";
form.style.display = "none";
// adding some input elements to the form...
// ...
// adding the file input
form.enctype = "multipart/form-data";
var fileInputs = jQuery("input:file");
fileInputs.each(function() {
if (this.value != "") {
form.appendChild(this);
}
});
form.action = "my.servlet.path";
form.submit();
EDIT: New info: I noticed in chrome devtools in the Network tab that the request status is "cancelled". What does that mean? The request does reach the server, so what was cancelled? And why?
Solved
Ok, I found the bug. The code I posted here is a simlified version of what's actually going on. What really happened was there was an update of some global data on the page before the form.submit()
, and KnockOut picked up on that update and updated the <input type="file">
with an empty value. And then obviously the file was not sent to the server.
After changing that, it works fine, but the request still shows up as cancelled in the Network tab. Don't know why...
链接地址: http://www.djcxy.com/p/36430.html上一篇: 从HTTP POST调用下载PDF