猿问

没有表格的文件上传

不使用任何形式,我可以<input type="file">使用jQuery使用POST方法将文件从发送到“ upload.php”。输入标签不在任何表单标签内。它单独站立。所以我不想使用jQuery插件,例如“ ajaxForm”或“ ajaxSubmit”。



明月笑刀无情
浏览 500回答 3
3回答

不负相思意

您可以使用FormData通过POST请求提交数据。这是一个简单的示例:var myFormData = new FormData();myFormData.append('pictureFile', pictureInput.files[0]);$.ajax({&nbsp; url: 'upload.php',&nbsp; type: 'POST',&nbsp; processData: false, // important&nbsp; contentType: false, // important&nbsp; dataType : 'json',&nbsp; data: myFormData});只要知道请求设置(例如url,方法和参数数据),就不必使用表单来发出ajax请求。

饮歌长啸

此处的所有答案仍在使用FormData API。就像"multipart/form-data"没有表格的上传一样。您还可以使用以下命令将文件作为内容直接上传到POST请求的正文中xmlHttpRequest:var xmlHttpRequest = new XMLHttpRequest();var file = ...file handle...var fileName = ...file name...var target = ...target...var mimeType = ...mime type...xmlHttpRequest.open('POST', target, true);xmlHttpRequest.setRequestHeader('Content-Type', mimeType);xmlHttpRequest.setRequestHeader('Content-Disposition', 'attachment; filename="' + fileName + '"');xmlHttpRequest.send(file);Content-Type和Content-Disposition标头用于解释我们要发送的内容(MIME类型和文件名)。我也在这里发布了类似的答案。

aluckdog

基于本教程,这里有一个非常基本的方法:$('your_trigger_element_selector').on('click', function(){&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; var data = new FormData();&nbsp; &nbsp; data.append('input_file_name', $('your_file_input_selector').prop('files')[0]);&nbsp; &nbsp; // append other variables to data if you want: data.append('field_name_x', field_value_x);&nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; type: 'POST',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; processData: false, // important&nbsp; &nbsp; &nbsp; &nbsp; contentType: false, // important&nbsp; &nbsp; &nbsp; &nbsp; data: data,&nbsp; &nbsp; &nbsp; &nbsp; url: your_ajax_path,&nbsp; &nbsp; &nbsp; &nbsp; dataType : 'json',&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; // in PHP you can call and process file in the same way as if it was submitted from a form:&nbsp; &nbsp; &nbsp; &nbsp; // $_FILES['input_file_name']&nbsp; &nbsp; &nbsp; &nbsp; success: function(jsonData){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; });&nbsp;});不要忘记添加适当的错误处理
随时随地看视频慕课网APP
我要回答