我在尝试通过 json/ajax 上传文件时遇到问题,并且文件看起来不像已上传。控制台输出中仅显示文件名。
我的html代码如下图。
<form action="/cgi-bin/upload.cgi" method="post" enctype="multipart/form-data" target="upIFrame">
<input type="file" id="uploadFileName" name="uploadFileName" size="30" >
<input type="button" id="upgradeFile" name="upgradeFile" value="Upload" onclick="ul.load()" />
<iframe id="upIFrame" name="upIFrame" src="#" style="display: none;"></iframe>
</form>
ul.load() 在下面调用这一行,最终 transfer.ajax 代码将调用
transfer.ajax({
url:'upload.cgi',
data:{filename: ul.filename},
success: success,
error: error,
async: true
});
ul.filename 来自uploadFileName
和 transfer.ajax 代码如下所示
transfer = {
ajax: function(p) {
if (p.url.indexOf('/') == -1) {
p.url = '/cgi-bin/' + p.url;
}
p.type = 'POST';
p.contentType = 'application/json';
p.dataType = 'json';
p.cache = false;
if (p.data != undefined) {
p.data = JSON.stringify(p.data);
}
$.ajax(p);
}
};
在 Fire Fox 中查看后的结果是 JSON
filename "file.tgz"
资源
{"filename":"file.tgz"}
有人能告诉我我做错了什么或错过了什么吗?
TIA
我将代码修改为以下...
var fd = new FormData();
fd.append("filename",ul.filename);
$.ajax({
url: "/cgi-bin/test.cgi",
type: "POST",
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
beforeSend : function(xhr){
xhr.setRequestHeader('Content-Disposition', 'form-data; name=\"uploadFileName\"; filename=\"' + ul.filename + '\"');
},
});
并且 Fire Fox 中的请求标头为
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Content-Disposition form-data; name="uploadFileName"; filename="test.tgz"
Content-Length 157
Content-Type multipart/form-data; boundary=---------------------------20025277823050
X-Requested-With XMLHttpRequest
但“帖子”显示以下内容
来源----------------------------20025277823050 内容处置:表单数据;名称="文件名"
test.tgz -----------------------------20025277823050--
我将如何包含文件名 =“test.tgz”?少了什么东西?
TIA