使用 React.js 上传文件

发布日期:2026-06-27 09:40:04   来源 : 杭州电子商务研究院    浏览量 :8
杭州电子商务研究院 发布日期:2026-06-27 09:40:04  
8

介绍

您可能从未在 React 或任何其他技术中处理过文件上传,但您很可能会遇到这样的需求,无论是更新用户的个人资料照片、CSV 文件还是 PDF,仅举几例。在本指南中,您将学习如何在 React 应用程序中上传文件。

设置应用程序

首先,在终端中运行以下命令,或访问https://react.new以通过https://codesandbox.io获取完全配置的 React 开发环境

      npx create-react-app <YOUR_APP_NAME>
    

<YOUR_APP_NAME>指的是您喜欢的应用程序名称。

接下来,创建一个具有带有上传按钮的文件输入的简单组件。

      import React from 'react';

function FileUploadPage(){
	return(
   <div>
			<input type="file" name="file" onChange={changeHandler} />
			<div>
				<button onClick={handleSubmission}>Submit</button>
			</div>
		</div>
	)
}
    

添加状态

现在向您的应用添加一些状态以包含有关用户选择的文件的信息。

      import React, {useState} from 'react';

function FileUploadPage(){
	const [selectedFile, setSelectedFile] = useState();
	const [isFilePicked, setIsFilePicked] = useState(false);

	return(
   <div>
			<input type="file" name="file" onChange={changeHandler} />
			<div>
				<button onClick={handleSubmission}>Submit</button>
			</div>
		</div>
	)
}
    

selectedFile包含有关当前选定文件的信息。

isFilePicked确定文件是否已被选中。

现在实现handleSubmissionchangeHandler事件处理程序,然后添加条件以显示当前选定文件的详细信息。

      import React, {useState} from 'react';

function FileUploadPage(){
	const [selectedFile, setSelectedFile] = useState();
	const [isFilePicked, setIsFilePicked] = useState(false);

	const changeHandler = (event) => {
		setSelectedFile(event.target.files[0]);
		setIsSelected(true);
	};

	const handleSubmission = () => {
	};

	return(
   <div>
			<input type="file" name="file" onChange={changeHandler} />
			<div>
				<button onClick={handleSubmission}>Submit</button>
			</div>
		</div>
	)
}
    

Event.target.files是一个对象,其中包含表单中选择要上传的文件的详细信息。

当前选定的文件对象也如下所示。

      {
		lastModified: 1588350162449
		lastModifiedDate: Fri May 01 2020 17:22:42 GMT+0100 (British Summer Time) {} // Date object
		name: "Pluralsight_logo.png"
		size: 68317
		type: "image/png"
		webkitRelativePath: ""
		__proto__: File
}
    

现在添加条件显示逻辑,向用户提供文件的详细信息。

      import React, {useState} from 'react';

function FileUploadPage(){
	const [selectedFile, setSelectedFile] = useState();
	const [isFilePicked, setIsFilePicked] = useState(false);

	const changeHandler = (event) => {
		setSelectedFile(event.target.files[0]);
		setIsSelected(true);
	};

	const handleSubmission = () => {
	};

	return(
   <div>
			<input type="file" name="file" onChange={changeHandler} />
			{isSelected ? (
				<div>
					<p>Filename: {selectedFile.name}</p>
					<p>Filetype: {selectedFile.type}</p>
					<p>Size in bytes: {selectedFile.size}</p>
					<p>
						lastModifiedDate:{' '}
						{selectedFile.lastModifiedDate.toLocaleDateString()}
					</p>
				</div>
			) : (
				<p>Select a file to show details</p>
			)}
			<div>
				<button onClick={handleSubmission}>Submit</button>
			</div>
		</div>
	)
}
    

使用 Fetch 上传文件

您可以使用 Fetch API 来实现文件上传,也可以使用 Axios 等库来实现上传逻辑。实现onClick处理程序(如下所示)来处理文件上传。

有一项免费服务可以通过其 API 上传文件,因此请继续在此处注册以获取 API 密钥。

      import React, {useState} from 'react';

function FileUploadPage(){
	const [selectedFile, setSelectedFile] = useState();
	const [isFilePicked, setIsFilePicked] = useState(false);

	const changeHandler = (event) => {
		setSelectedFile(event.target.files[0]);
		setIsSelected(true);
	};

	const handleSubmission = () => {
		const formData = new FormData();

		formData.append('File', selectedFile);

		fetch(
			'https://freeimage.host/api/1/upload?key=<YOUR_API_KEY>',
			{
				method: 'POST',
				body: formData,
			}
		)
			.then((response) => response.json())
			.then((result) => {
				console.log('Success:', result);
			})
			.catch((error) => {
				console.error('Error:', error);
			});
	};
	};

	return(
   <div>
			<input type="file" name="file" onChange={changeHandler} />
			{isSelected ? (
				<div>
					<p>Filename: {selectedFile.name}</p>
					<p>Filetype: {selectedFile.type}</p>
					<p>Size in bytes: {selectedFile.size}</p>
					<p>
						lastModifiedDate:{' '}
						{selectedFile.lastModifiedDate.toLocaleDateString()}
					</p>
				</div>
			) : (
				<p>Select a file to show details</p>
			)}
			<div>
				<button onClick={handleSubmission}>Submit</button>
			</div>
		</div>
	)
}
    

这里发生了什么?您结合使用了 fetch API 和FormData原生 Javascript API 将文件发布到文件服务器。

成功发布到服务器应该会产生以下响应。

      {
							"status_code": 200,
							"success": {
								"message": "image uploaded",
								"code": 200
							},
							"image": {
								"name": "example",
								"extension": "png",
								"size": 53237,
								"width": 1151,
								"height": 898,
								"date": "2020-11-11 15:32:33",
								"date_gmt": "2020-11-11 19:32:33",
								"storage_id": null,
								"description": null,
								"nsfw": "0",
								"md5": "d973298h0d722c956c3629870299735830",
								"storage": "datefolder",
								"original_filename": "pluralsight_logo.png",
								"original_exifdata": null,
								"views": "0",
								"id_encoded": "L",
								"filename": "pluralsight_logo.png",
								"ratio": 1.2817371937639,
								"size_formatted": "52 KB",
								"mime": "image/png",
								"bits": 8,
								"channels": null,
								"url": "http://freeimage.host/images/2020/11/11/pluralsight_logo.png",
								"url_viewer": "http://freeimage.host/image/L",
								"thumb": {
									"filename": "example.th.png",
									"name": "example.th",
									"width": 160,
									"height": 160,
									"ratio": 1,
									"size": 17848,
									"size_formatted": "17.4 KB",
									"mime": "image/png",
									"extension": "png",
									"bits": 8,
									"channels": null,
									"url": "http://freeimage.host/images/2020/11/11/pluralsight_logo.th.png"
								},
								"medium": {
									"filename": "pluralsight_logo.md.png",
									"name": "pluralsight_logo.md",
									"width": 500,
									"height": 390,
									"ratio": 1.2820512820513,
									"size": 104448,
									"size_formatted": "102 KB",
									"mime": "image/png",
									"extension": "png",
									"bits": 8,
									"channels": null,
									"url": "http://freeimage.host/images/2020/11/11/pluralsight_logo.md.png"
								},
								"views_label": "views",
								"display_url": "http://freeimage.host/images/2020/11/11/pluralsight_logo.md.png",
								"how_long_ago": "moments ago"
							},
							"status_txt": "OK"
						}
    

结论

就这样结束了。在本指南中,您学习了如何使用 React 上传文件以及如何使用 Fetch API 上传文件。如果您想了解有关 Fetch API 和 formData API 的更多信息,以下资源将有所帮助:

  1. <a href="https://translate.google.com/website?sl=en&tl=zh-CN&hl=zh-CN&client=webapp&u=https://developer.mozilla.org/en-US

以上内容来自杭州电子商务研究院推送
关注
关于我们
热门推荐
合作伙伴
免责声明:本站部分资讯来源于网络,如有侵权请及时联系客服,我们将尽快处理
Copyright © 2025-2027 ToB产业网址导航 公安备案 浙公网安备33010602013138号 浙ICP备16025413号-9
支持 反馈 关注 数据