簡體   English   中英

表單提交(POST)后,Javascript FileReader.onload無法正常工作

[英]Javascript FileReader.onload not working after a form submit (POST)

目前,我正在創建一個頁面上傳器。 我使用Javascript(+ jQuery)開發並且使用AppJS

此上載器有2種形式,其中上載輸入可用。 一頁中的兩種形式和第二種形式都隱藏display: none;

兩者都使用相同的定制上傳擴展名。

  • 在第一種形式中,我要求提供2張圖像,必須將其刪除。

  • 當我放下圖像時,它通過套接字上傳到我的nodejs服務器並正確保存。

  • 當我再次放下第二個文件時,它被上傳到我的nodejs服務器並正確保存。

  • 然后我將表單發布到我的nodejs服務器

  • 之后,我.hide()的第一種形式和.show()的第二個。

當我再次使用上載插件時,沒有錯誤出現,但是也沒有文件上傳。

我注意到在發布第一個表單后,不執行FileReader.onload。

在一些示例代碼下,我無法發布整個應用程序。

HTML

<form id="formone" action="/formone">
    <input type="text" name="background" value="Drop here" class="uploadinput" readonly />
    <input type="text" name="logo" value="Drop here" class="uploadinput" readonly />
</form>
<form id="formtwo" action="/formtwo" style="display:none;">
    <input type="text" name="icon" value="Drop here" class="uploadinput" readonly />
</form>

Java腳本

// File upload extension
$.fn.extend({
    filedrop: function() {
        return this.each(function() {
            var files = []
            var $this = $(this)

            // Catch drop event
            $this.bind('drop', function(event) {
                event.stopPropagation()
                event.preventDefault()

                console.log('Dropped') // Works in both forms

                files = event.originalEvent.target.files || event.originalEvent.dataTransfer.files

                file = files[0]

                var reader = new FileReader()

                // reader.onload only works in form 1
                reader.onload = function(e) {
                    var buffer = e.target.result
                    socket.emit('uploadfile', file.name, buffer)
                }

                reader.onerror = function(error) {
                    console.log("error", error)
                    console.log(error.getMessage())
                }

                reader.readAsBinaryString(file)

                return false
            })
        })
    }
})

$('.uploadinput').filedrop()

window.showFormTwo = function() {
    $('#formone').hide()
    $('#formtwo').show()
}

Node.js

app.router.post('/formone', function() {
    window.showFormTwo()
})

javascript加載后,就會立即調用函數filedrop,但是此時您的form2被隱藏了。 綁定 API:

將處理程序附加到jQuery對象中當前選定的元素上,因此這些元素必須在對.bind()的調用發生時存在。 有關更靈活的事件綁定,請參見.on()或.delegate()中有關事件委托的討論。

因此,因為form2是隱藏的,所以drop事件永遠不會綁定,並且它的事件處理函數也永遠不會被調用。 reader.onload位於此事件處理程序內。 .on是將事件處理函數附加到元素的首選方法。

所以改變這個

$this.bind('drop', function(event) {

$this.on('drop', function(event) {

暫無
暫無

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

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