使用js实现功能:使用POST方式提交一个文件到服务器端,并给出js代码
时间: 2024-02-09 09:08:39 浏览: 28
以下是使用JavaScript发送POST请求上传文件的示例代码:
```js
const fileInput = document.getElementById('fileInput'); // 获取文件输入框
const uploadButton = document.getElementById('uploadButton'); // 获取上传按钮
uploadButton.addEventListener('click', () => {
const file = fileInput.files[0]; // 获取文件对象
const formData = new FormData(); // 创建FormData对象
formData.append('file', file); // 将文件对象添加到FormData对象中
fetch('/upload', { // 发送POST请求
method: 'POST',
body: formData
})
.then(response => {
console.log('上传成功');
})
.catch(error => {
console.error('上传失败', error);
});
});
```
其中,`fileInput`和`uploadButton`分别表示文件输入框和上传按钮的DOM元素,`/upload`表示上传接口的URL,根据实际情况进行修改。在点击上传按钮时,首先获取文件对象,然后创建一个`FormData`对象,并将文件对象添加到其中。最后使用`fetch`方法发送POST请求,将`FormData`对象作为请求体发送到服务器端。在上传成功或失败时,分别输出相应的日志信息。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)