简体   繁体   English

如何使用 blazor 客户端应用程序在服务器上创建新文件?

[英]How to create a new file on the server with blazor client-side application?

I am trying to create a new file on the web server by clicking a button on the client page.我正在尝试通过单击客户端页面上的按钮在 web 服务器上创建一个新文件。

Browser console shows only "WASM: File created."浏览器控制台仅显示“WASM:已创建文件”。 but does not show any errors or warnings about the file operations.但不显示有关文件操作的任何错误或警告。

There are not any new files under the path /wwwroot either. /wwwroot 路径下也没有任何新文件。

Blazor server is running on localhost (Win10) as administrator. Blazor 服务器以管理员身份在 localhost (Win10) 上运行。

Index.razor content;索引.razor内容;

@page "/"

<h1>Demo1</h1>

<button type="submit" @onclick="CreateFile.Run">Create A New File</button>

@code 
{
    public class CreateFile
    {

        public static void Run()
        {
            System.IO.File.WriteAllText("test.txt", "hello world");
            System.IO.File.WriteAllText(@"C:\VS Code Projects\Demo1\Client\wwwroot\samplefile.txt", "content 123");
            Console.WriteLine("File created.");

        }
    }
}

This isn't possible.这是不可能的。 Your code is running on the client not on the server and you don't have access to the file system on the client.您的代码在客户端而不是服务器上运行,并且您无权访问客户端上的文件系统。

If you want to do things like this you need to use a Blazor Server App rather than a Blazor WebAssembly App.如果你想做这样的事情,你需要使用 Blazor 服务器应用程序而不是 Blazor WebAssembly 应用程序。

This message: "WASM: File created."此消息:“WASM:文件已创建。” indicates that you're using a Blazor WebAssembly App, right?表示您使用的是 Blazor WebAssembly 应用程序,对吗? The browser is not supposed to allow you to create a file on the client.浏览器不应该允许您在客户端上创建文件。 This is only a message produced by your code.这只是您的代码生成的消息。

Understand this: When you hit the button a normal post back occurs because the type of the button is 'submit'.理解这一点:当您点击按钮时,会发生正常的回发,因为按钮的类型是“提交”。 After the return to the calling page, I guess, a click event is triggered (not sure but it may be so), and the code in the run method is executed to display the message "WASM: File created."返回调用页面后,我猜是触发了点击事件(不确定但可能是这样),执行run方法中的代码,显示消息“WASM:文件已创建”。

Understand this: You've created a Blazor WebAssembly App server hosted.了解这一点:您已经创建了一个托管的 Blazor WebAssembly 应用服务器。 This is a Single Page Application, and it should communicate with your server via a Web Api or SignleR.这是一个单页应用程序,它应该通过 Web Api 或 SignleR 与您的服务器通信。 You must not use post backs, and you need to learn how the two modes of executions of Blazor work.你不能使用回传,你需要了解 Blazor 的两种执行模式是如何工作的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM