簡體   English   中英

如何使用javascript發送文件

[英]How to send file using javascript

我正在嘗試制作一個需要上傳文件的上傳頁面。 我在這里使用 Spring 框架,我的查詢位於上傳按鈕上,我正在調用一個 JavaScript 方法,該方法應該使用 jQuery AJAX 將我的文件發送到控制器。 有沒有辦法通過 JavaScript 傳遞它?

以下是我正在嘗試的代碼。

<body>
    <div style="text-align: center; margin-top: 60px;">
        <form enctype="multipart/form-data">
            Select file:
            <input type="file" name="dataFile" id="fileAttachment"/><br/><br/>
                <div style="text-align: center; margin-top: 100px;">
                    <input style="cursor: pointer;" onmouseover="" onclick="uploadAttachment()" class="dialogbox" type="submit" value="Upload Report" />
                </div>
        </form>
    </div>
</body>

JS:

<script language="Javascript">
function uploadAttachment(){
    var Name = jQuery('#Name option:selected').text();
    jQuery.post('upload',{Name:Name}
    function(data){
    if(data==1)
    alert("success");
    else
    alert("failed");
    });
}
    </script>

在controller.java頁面下面是寫的代碼

@RequestMapping(value = "upload", method=RequestMethod.POST)
        public @ResponseBody String upload(HttpServletRequest request, HttpServletResponse response,
@RequestParam("Name") String Name){
System.out.println(Name);
}

如果您實際上正在尋找一種純粹的 javascript 方式來上傳圖像/文件,那么以下 2009 年的教程將告訴您如何做到這一點:

http://igstan.ro/posts/2009-01-11-ajax-file-upload-with-pure-javascript.html

當我想向表單提交添加基本身份驗證而不啟用 cookie 時,我遇到了這個問題。 例如,當您有包含文件名、文件等字段的用戶名/密碼字段時。

希望這可以幫助!

我認為您可以嘗試使用以下代碼使用 javascript 上傳文件。

function uploadAttachment(){
  $('#fileAttachment').trigger('click');

  if (typeof timer != 'undefined') {
      clearInterval(timer);
  }

  timer = setInterval(function() {
      if ($('#fileAttachment').val() != '') {
          clearInterval(timer);

          $.ajax({
              url: 'YOUR_UPLOAD_URL',
              type: 'post',
              dataType: 'json',
              data: new FormData($('#fileAttachment').closest('form')[0]),
              cache: false,
              contentType: false,
              processData: false,
              success: function(response){
              }
          });
      }
  }, 500);
}

您需要將YOUR_UPLOAD_URL替換為您的服務器上傳 URL。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM