酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

jquery实现文件上传,不用插件

在jQuery中实现文件上传,通常我们会使用`FormData`对象和`XMLHttpRequest`对象来发送POST请求。以下是一个简单的示例: ```html <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <form id="file-upload-form"> <input type="file" id="file-input" name="file"> <button type="submit">Upload</button> </form> <script> $(document).ready(function(){ $('#file-upload-form').on('submit', function(e){ e.preventDefault(); // 阻止表单默认提交行为 var fileInput = document.getElementById('file-input'); var file = fileInput.files[0]; if(file) { var formData = new FormData(); formData.append('file', file); $.ajax({ url: 'your-url-to-upload', // 你的服务器上传接口 type: 'POST', data: formData, processData: false, // 不处理数据 contentType: false, // 不设置Content-Type xhr: function () { var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener('progress', function (event) { if (event.lengthComputable) { var percentComplete = event.loaded / event.total; console.log(percentComplete); } }, false); return xhr; }, success: function(response){ console.log('File uploaded successfully:', response); }, error: function(xhr, status, error){ console.error('Error uploading file:', error); } }); } else { alert('Please select a file to upload.'); } }); }); </script> </body> </html> ``` 在这个例子中,当用户选择一个文件并点击上传按钮时,会阻止表单的默认提交行为,然后创建一个`FormData`对象并将文件添加到其中。然后使用`$.ajax`发送POST请求到服务器,同时监听上传进度。如果上传成功,会在控制台打印出响应信息;如果上传失败,会打印错误信息。 这个示例假设你已经有了一个服务器端接收文件上传的接口。你需要将其替换为实际的URL。 [2024-04-02 09:54:50 | AI写代码神器 | 475点数解答]

相关提问