我想用jQuery异步上传文件。

$(文档).ready(函数(){$(“#uploadbutton”).click(函数(){var filename=$(“#file”).val();$.ajax美元({类型:“POST”,url:“addFile.do”,enctype:'多部分/表单数据',数据:{文件:文件名},成功:函数(){alert(“上传的数据:”);}});});});<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js“></script><span>文件</span><input type=“file”id=“file”name=“file”size=“10”/><input id=“uploadbutton”type=“button”value=“Upload”/>

我只得到文件名,而不是上传文件。我可以做什么来解决这个问题?


当前回答

Simple Ajax Uploader是另一个选项:

https://github.com/LPology/Simple-Ajax-Uploader

跨浏览器——适用于IE7+、Firefox、Chrome、Safari和Opera支持多个并发上传——即使在非HTML5浏览器中也是如此没有flash或外部CSS——只有一个5Kb的Javascript文件可选,内置支持完全跨浏览器进度条(使用PHP的APC扩展)灵活且高度可定制——使用任何元素作为上传按钮,设置自己的进度指示器不需要表单,只需提供一个元素作为上传按钮麻省理工学院许可证——在商业项目中免费使用

示例用法:

var uploader = new ss.SimpleUpload({
    button: $('#uploadBtn'), // upload button
    url: '/uploadhandler', // URL of server-side upload handler
    name: 'userfile', // parameter name of the uploaded file
    onSubmit: function() {
        this.setProgressBar( $('#progressBar') ); // designate elem as our progress bar
    },
    onComplete: function(file, response) {
        // do whatever after upload is finished
    }
});

其他回答

你也可以考虑使用类似的https://uppy.io.

它可以在不离开页面的情况下进行文件上传,并提供一些奖励,如拖放、在浏览器崩溃/网络不稳定的情况下恢复上传,以及从例如Instagram导入。它是开源的,不依赖于jQuery/React/Angular/Vue,但可以与它一起使用。免责声明:作为它的创建者,我有偏见;)

我找到的一个解决方案是让<form>以隐藏iFrame为目标。iFrame然后可以运行JS向用户显示它已完成(页面加载时)。

为此,我建议使用Fine Uploader插件。您的JavaScript代码为:

$(document).ready(function() {
  $("#uploadbutton").jsupload({
    action: "addFile.do",
    onComplete: function(response){
      alert( "server response: " + response);
    }
  });
});

你可以很容易地用普通JavaScript实现。以下是我当前项目的片段:

var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(e) {
    var percent = (e.position/ e.totalSize);
    // Render a pretty progress bar
};
xhr.onreadystatechange = function(e) {
    if(this.readyState === 4) {
        // Handle file upload complete
    }
};
xhr.open('POST', '/upload', true);
xhr.setRequestHeader('X-FileName',file.name); // Pass the filename along
xhr.send(file);

这个AJAX文件上传jQuery插件在某处上传文件,并传递对回调的响应。

它不依赖于特定的HTML,只需给它一个<input-type=“file”>它不要求服务器以任何特定方式响应使用多少文件或文件在页面上的位置无关紧要

--尽可能少地使用--

$('#one-specific-file').ajaxfileupload({
  'action': '/upload.php'
});

--或者--

$('input[type="file"]').ajaxfileupload({
  'action': '/upload.php',
  'params': {
    'extra': 'info'
  },
  'onComplete': function(response) {
    console.log('custom handler for file:');
    alert(JSON.stringify(response));
  },
  'onStart': function() {
    if(weWantedTo) return false; // cancels upload
  },
  'onCancel': function() {
    console.log('no file selected');
  }
});