jQuery 无格式文件上传

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19617996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:18:33  来源:igfitidea点击:

File Upload without Form

javascriptjqueryhtml

提问by Elo Peri

Without using any forms whatsoever, can I just send a file/files from <input type="file">to 'upload.php' using POST method using jQuery. The input tag is not inside any form tag. It stands individually. So I don't want to use jQuery plugins like 'ajaxForm' or 'ajaxSubmit'.

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

回答by Omid Monshizadeh

You can use FormDatato submit your data by a POST request. Here is a simple example:

您可以使用FormData通过 POST 请求提交数据。这是一个简单的例子:

var myFormData = new FormData();
myFormData.append('pictureFile', pictureInput.files[0]);

$.ajax({
  url: 'upload.php',
  type: 'POST',
  processData: false, // important
  contentType: false, // important
  dataType : 'json',
  data: myFormData
});

You don't have to use a form to make an ajax request, as long as you know your request setting (like url, method and parameters data).

您不必使用表单来发出 ajax 请求,只要您知道您的请求设置(如 url、方法和参数数据)。

回答by Wilt

All answers here are still using the FormData API. It is like a "multipart/form-data"upload without a form. You can also upload the file directly as content inside the body of the POSTrequest using xmlHttpRequestlike this:

这里的所有答案仍然使用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-Typeand Content-Dispositionheaders are used for explaining what we are sending (mime-type and file name).

Content-TypeContent-Disposition标题用于解释我们发送的内容(mime 类型和文件名)。

I posted similar answer also here.

我也在这里发布了类似的答案。

回答by Amazzing

Basing on this tutorial, here a very basic way to do that:

基于本教程,这里有一个非常基本的方法来做到这一点:

$('your_trigger_element_selector').on('click', function(){    
    var data = new FormData();
    data.append('input_file_name', $('your_file_input_selector').prop('files')[0]);
    // append other variables to data if you want: data.append('field_name_x', field_value_x);

    $.ajax({
        type: 'POST',               
        processData: false, // important
        contentType: false, // important
        data: data,
        url: your_ajax_path,
        dataType : 'json',  
        // in PHP you can call and process file in the same way as if it was submitted from a form:
        // $_FILES['input_file_name']
        success: function(jsonData){
            ...
        }
        ...
    }); 
});

Don't forget to add proper error handling

不要忘记添加适当的错误处理

回答by Hadiyal Rakesh

Step 1: Create HTML Page where to place the HTML Code.

步骤 1:创建 HTML 页面以放置 HTML 代码。

Step 2: In the HTML Code Page Bottom(footer)Create Javascript: and put Jquery Code in Script tag.

步骤 2:在 HTML 代码页底部(页脚)创建 Javascript:并将 Jquery 代码放入 Script 标签中。

Step 3: Create PHP File and php code copy past. after Jquery Code in $.ajaxCode url apply which one on your php file name.

第 3 步:创建 PHP 文件并将 php 代码复制过去。在$.ajax代码 url 中的Jquery 代码之后应用您的 php 文件名中的哪一个。

JS

JS

//$(document).on("change", "#avatar", function() {   // If you want to upload without a submit button 
$(document).on("click", "#upload", function() {
  var file_data = $("#avatar").prop("files")[0]; // Getting the properties of file from file field
  var form_data = new FormData(); // Creating object of FormData class
  form_data.append("file", file_data) // Appending parameter named file with properties of file_field to form_data
  form_data.append("user_id", 123) // Adding extra parameters to form_data
  $.ajax({
    url: "/upload_avatar", // Upload Script
    dataType: 'script',
    cache: false,
    contentType: false,
    processData: false,
    data: form_data, // Setting the data attribute of ajax with file_data
    type: 'post',
    success: function(data) {
      // Do something after Ajax completes 
    }
  });
});

HTML

HTML

<input id="avatar" type="file" name="avatar" />
<button id="upload" value="Upload" />

Php

php

print_r($_FILES);
print_r($_POST);

回答by Shabi_669

Sorry for being that guybut AngularJS offers a simple and elegant solution.

很抱歉成为那个人,但 AngularJS 提供了一个简单而优雅的解决方案。

Here is the code I use:

这是我使用的代码:

ngApp.controller('ngController', ['$upload',
function($upload) {

  $scope.Upload = function($files, index) {
    for (var i = 0; i < $files.length; i++) {
      var file = $files[i];
      $scope.upload = $upload.upload({
        file: file,
        url: '/File/Upload',
        data: {
          id: 1 //some data you want to send along with the file,
          name: 'ABC' //some data you want to send along with the file,
        },

      }).progress(function(evt) {

      }).success(function(data, status, headers, config) {
          alert('Upload done');
        }
      })
    .error(function(message) {
      alert('Upload failed');
    });
  }
};
}]);
.Hidden {
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div data-ng-controller="ngController">
  <input type="button" value="Browse" onclick="$(this).next().click();" />
  <input type="file" ng-file-select="Upload($files, 1)" class="Hidden" />
</div>

On the server side I have an MVC controller with an action the saves the files uploaded found in the Request.Files collection and returning a JsonResult.

在服务器端,我有一个 MVC 控制器,它带有一个动作,可以保存在 Request.Files 集合中找到的上传文件并返回一个 JsonResult。

If you use AngularJS try this out, if you don't... sorry mate :-)

如果你使用 AngularJS 试试这个,如果你不......对不起,伙计:-)

回答by Rodrigo Azevedo

Try this puglin simpleUpload, no need form

试试这个 puglin simpleUpload,不需要表格

Html:

网址:

<input type="file" name="arquivo" id="simpleUpload" multiple >
<button type="button" id="enviar">Enviar</button>

Javascript:

Javascript:

$('#simpleUpload').simpleUpload({
  url: 'upload.php',
  trigger: '#enviar',
  success: function(data){
    alert('Envio com sucesso');

  }
});