提问人:ednel 提问时间:10/19/2023 最后编辑:Brian Tompsett - 汤莱恩ednel 更新时间:10/19/2023 访问量:78
如何在 React js 中移动文件
How to move files in React js
问:
我有应用程序,我使用 laravel 作为我的后端来制作 API,我使用 react 作为我的前端。因此,在我的反应前端中,我设法使用axios获取.txt中的文件,并处理该文件并将其保存到数据库中。现在,在处理该文件后,应该将其删除在以前的目录中并移动到其他目录,所以我的问题是如何移动该文件?
这是我的代码:
axios
.get("docuin/incoming.xml", {
"Content-Type": "application/xml; charset=utf-8",
})
.then((response) => {
var xml = new XMLParser().parseFromString(response.data);
var from = xml.getElementsByTagName("ID")[0].value;
//from here i can send to DB using post axios,after sucessful sent now it should move into "docout/outgoing.xml"
});
我试图通过 axios 帖子发送它,但带来了错误。
答:
-1赞
David Teo
10/19/2023
#1
为了在应用程序中将文件从一个目录移动到另一个目录,您必须使用服务器端语言(如 PHP(在您的情况下为 Laravel)来处理文件操作。
React 本身不能直接执行文件系统操作。
首先,您必须创建一个路由来处理 Laravel 项目中的文件移动操作。
例如,在 routes/api.php 文件中,添加以下路由:
Route::post('/move-file', 'FileController@moveFile');
使用此命令创建新控制器。
php artisan make:controller FileController
在 FileController 的 moveFile 函数中,您可以添加这样的功能。
public function moveFile(Request $request) { $sourcePath = 'path/to/source/file.txt'; $destinationPath = 'path/to/destination/file.txt'; try { // Move the file if (File::move($sourcePath, $destinationPath)) { return response()->json(['message' => 'File moved successfully']); } else { return response()->json(['message' => 'Failed to move file'], 500); } } catch (\Exception $e) { return response()->json(['message' => 'An error occurred while moving the file'], 500); } }
在你的 React 代码中,你可以处理来自 Laravel 后端的响应。
axios .post('/move-file') .then((response) => { console.log(response.data.message); }) .catch((error) => { console.log('Error:', error.response.data.message); });
您必须在 Laravel 应用程序中正确配置文件路径和目录,以确保将文件移动到正确的位置。
评论
0赞
ednel
10/19/2023
谢谢!!所以从你上面的观点来看,我的文件管理应该只在后端 API 上完成,对吧?
0赞
David Teo
10/19/2023
是的,对。你现在明白了重点。凝聚力。我的回答有没有帮助?
评论