处理 html5 表单上传(文件)

发布于 2024-12-10 00:46:48 字数 928 浏览 1 评论 0原文

我在使用“非常简单”的文件上传表单时遇到了 3 个问题(!)。我将尝试简短地解释:-):

1.) 当将文件发送到服务器脚本位置时,如action="" 中给出的那样,我不想打开一个新窗口! 但事实上,当我提交一个空白窗口时。所以现在,我用 target="_blank" 打开它。有没有办法说 “只需执行您的操作,将数据发送到脚本,但不要打开任何窗口或内容?”或“关闭空白窗口 当你打开它时:-)?

2.) 你知道一种像ajax一样通过表单发送http-header字段的方法吗?我需要发送一个身份验证

3.) 您建议在成功发送数据后使用哪个事件(html5 新事件?)来执行(在 ajax 中我总是使用 “完成或成功的事件,有类似表格的东西吗?)

:困惑:感谢您的建议

<form id="uploaddata" enctype="multipart/form-data" method="post" action="/cgi-bin/send/?auth='+sessionStorage.logindata+'" target="_blank">
<input type="hidden" name="folder" value="'+PATH+'" />
<input id="file" type="file" class="choosefile" max="999" min="1" name="attach" filename="" accept="">
<input type="button" id="formupload" class="submitupload" value="Upload">
<input type="submit"  class="submitupload button" value="Upload">                                         
</form>

i have 3 problems (!) using a "mighty simple" file-upload-form. i will try to explain shortly :-):

1.) when sending the file to the server script-location as given in action="" I DO NOT want to open a new window!
But in fact, when i submit a blank window apperas. So for now, i open it with target="_blank". Is there a way to say
"Just do your action, send the data to the sript but DO NOT open any window or content?" or "close the blank window
as soon as you opened it :-)?

2.) do you know a way to send http-header fields around with the form just like with ajax? i need to send an authetification

3.) which event (html5 new one?) would you suggest to use to execute AFTER having send the data successfully (in ajax i always use
"complete or success events, is there sth. like that for forms?)

:confused: thanks for your suggestions

<form id="uploaddata" enctype="multipart/form-data" method="post" action="/cgi-bin/send/?auth='+sessionStorage.logindata+'" target="_blank">
<input type="hidden" name="folder" value="'+PATH+'" />
<input id="file" type="file" class="choosefile" max="999" min="1" name="attach" filename="" accept="">
<input type="button" id="formupload" class="submitupload" value="Upload">
<input type="submit"  class="submitupload button" value="Upload">                                         
</form>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

高冷爸爸 2024-12-17 00:46:48

如果不使用 AJAX,您将失去此表单的许多必需条件。

通过使用 AJAX,您可以:
1. 防止弹出窗口
2.添加额外的标题
3. 有一个事件

如果没有 AJAX,表单的提交操作必须去某个地方,无论是弹出窗口还是同一个窗口。您对该帖子的回复将决定浏览器中显示的内容。

因此,您可以通过发回另一个包含所需操作的网页来在服务器端解决问题 1 和 3。

问题 2 您可以使用 GET 方法而不是 post 方法作为查询字符串发送,尽管它们不会是标头,您可以使用隐藏的表单字段,但这在大多数情况下并不理想。此外,使用 post 表单中的所有内容都会随数据包发送到服务器并且可以读取,但同样不在标头中。

我建议仅使用 AJAX 来解决您的问题,由于其异步和可定制的性质,它似乎很适合您的问题。

编辑:
正如您所询问的 iframe 功能,这里是表单信息:

<form id="fileAPITesting" action="startStopResume.aspx" method="POST" target="upload_target" enctype="multipart/form-data" encoding="multipart/form-data">    
      <input type="file" id="fileInput"  name="fileInput"  />
      <button id="submit" type="submit" >Submit</button>  
    </form>
<iframe id="upload_target" name="upload_target" src="#" style="display:none;"></iframe>

这将自动将发布功能重定向到 iframe。然后您可以添加一些代码(这里我使用 jQuery 来简化)来防止这种情况并使用您的 AJAX:

<script type="text/javascript">
        $('#fileAPITesting').bind('submit', function(e){
            e.preventDefault();         
            fileProcessing(document.getElementById('fileInput'));       
        });
        setStatusArea();        
    </script>

在这里,jQuery 表单插件变得非常方便。另外值得注意的是,如果您链​​接到 jQuery 的 Google 代码存储库,那么您很可能不会增加页面的开销,因为许多其他页面使用 jQuery 并且它会在用户的缓存中。以下是该页面的链接:

http://plugins.jquery.com/project/form

我的表单还有很多其他要求,但这里是我的后端页面的示例:

function fileProcessing(fileToProcess){ 
    // grab file information only allows 1 file at a time
    // In IE have to grab differently
    if(window.File){
        file = fileToProcess.files[0];
        clearForm(false);
        if (file){
            fileLength = file.size;
            fileName = file.name;
            totalBLObs = Math.ceil((fileLength / BYTES_PER_CHUNK));         
            initialInformation();
            $('#stop').toggle();
            hideButtons();
            $('#pause').toggle();
            fileSending();
        }else{
            statusField('No file selected');
        }
    }else{
        // without a the file API we have to submit the entire form to an iframe
        file = fileToProcess;
        clearForm(false);
        fileAPI = false;
        time = new Date();      
        if(file.value){
            // IE cannot get a proper handle on the information
            hideButtons();
            fileName = file.value;
            fileName = fileName.substr(fileName.lastIndexOf('\\') + 1);
            statusField('<br />The File API is not implemented.' + 
                '<br />Attempting alternate method with only start & stop status' + 
                '<br />Started at: ' + time.toLocaleTimeString());          
            $('#fileAPITesting').ajaxSubmit({

                beforeSubmit: function(a,f,o) {
                    o.dataType = 'string';                  
                    try{                        
                        $('#uploadOutput').html('<img src="images/loaderb64.gif"' +  
                            'alt="loading" /><br />Submitting...');
                        $('#uploadOutput').show();
                    }catch(e){
                        statusField('<br />Submitting...');
                    }
                },
                success: function(data) {           
                    if (typeof data == 'object' && data.nodeType)
                        data = elementToString(data.documentElement, true);
                    else if (typeof data == 'object')
                        data = objToString(data);
                    time = new Date();
                    statusField('<br />'+ data + ' at ' + time.toLocaleTimeString());
                    try{
                        $('#progress').hide();
                        $('#progress').html('');
                    }catch(e){
                        // #progress doesn't exist
                    }
                }
            });
        }else{
            statusField('No file selected');
        }
    }   
};

希望能让您走上正确的道路。

Without using AJAX you will lose a lot of your requisites with this form.

By using AJAX you can:
1. prevent a popup
2. add your extra headers
3. have an event

Without AJAX your form's submit action has to go somewhere, whether a popup or the same window. Your response from the post will determine what displays in the browser.

So, you can take care of problems 1 and 3 on the server side by sending back another webpage which contains the desired actions.

Problem 2 you can send as a query string using the GET method instead of the post method, though they won't be headers, you can use hidden form fields, but this is less than desirable in most cases. Also, using the post everything in the form is sent with the packet to the server and can be read, but again not in the headers.

I would suggest merely using AJAX to solve your problems, due to its asynchronous and customizable nature, it seems to be a good fit for your problem.

EDIT:
As you've asked about the iframe functionality, here's the form info:

<form id="fileAPITesting" action="startStopResume.aspx" method="POST" target="upload_target" enctype="multipart/form-data" encoding="multipart/form-data">    
      <input type="file" id="fileInput"  name="fileInput"  />
      <button id="submit" type="submit" >Submit</button>  
    </form>
<iframe id="upload_target" name="upload_target" src="#" style="display:none;"></iframe>

This will automatically redirect the post functions to the iframe. You can then add some code (here I'm using jQuery to simplify) to prevent this and use your AJAX:

<script type="text/javascript">
        $('#fileAPITesting').bind('submit', function(e){
            e.preventDefault();         
            fileProcessing(document.getElementById('fileInput'));       
        });
        setStatusArea();        
    </script>

Here, the jQuery Form Plugin becomes quite handy. Also of note, if you link to the Google code repository for jQuery there is a good chance you won't add overhead to your page, as many other pages use jQuery and it would be in the user's cache. Here is a link to that page:

http://plugins.jquery.com/project/form

I have a multitude of other requirements with my form, but here is a sample of my backend page:

function fileProcessing(fileToProcess){ 
    // grab file information only allows 1 file at a time
    // In IE have to grab differently
    if(window.File){
        file = fileToProcess.files[0];
        clearForm(false);
        if (file){
            fileLength = file.size;
            fileName = file.name;
            totalBLObs = Math.ceil((fileLength / BYTES_PER_CHUNK));         
            initialInformation();
            $('#stop').toggle();
            hideButtons();
            $('#pause').toggle();
            fileSending();
        }else{
            statusField('No file selected');
        }
    }else{
        // without a the file API we have to submit the entire form to an iframe
        file = fileToProcess;
        clearForm(false);
        fileAPI = false;
        time = new Date();      
        if(file.value){
            // IE cannot get a proper handle on the information
            hideButtons();
            fileName = file.value;
            fileName = fileName.substr(fileName.lastIndexOf('\\') + 1);
            statusField('<br />The File API is not implemented.' + 
                '<br />Attempting alternate method with only start & stop status' + 
                '<br />Started at: ' + time.toLocaleTimeString());          
            $('#fileAPITesting').ajaxSubmit({

                beforeSubmit: function(a,f,o) {
                    o.dataType = 'string';                  
                    try{                        
                        $('#uploadOutput').html('<img src="images/loaderb64.gif"' +  
                            'alt="loading" /><br />Submitting...');
                        $('#uploadOutput').show();
                    }catch(e){
                        statusField('<br />Submitting...');
                    }
                },
                success: function(data) {           
                    if (typeof data == 'object' && data.nodeType)
                        data = elementToString(data.documentElement, true);
                    else if (typeof data == 'object')
                        data = objToString(data);
                    time = new Date();
                    statusField('<br />'+ data + ' at ' + time.toLocaleTimeString());
                    try{
                        $('#progress').hide();
                        $('#progress').html('');
                    }catch(e){
                        // #progress doesn't exist
                    }
                }
            });
        }else{
            statusField('No file selected');
        }
    }   
};

Hope that starts you down the right path.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文