1
\$\begingroup\$

How would I create a button for the user to click and be able to upload a text file from his desktop let's say?

I'd like to know about both, computer and mobiles.

\$\endgroup\$
  • 2
    \$\begingroup\$ Opening a file explorer in run time? \$\endgroup\$ – Hellium Dec 18 '17 at 11:57
  • 1
    \$\begingroup\$ Can we assume that you already know how to do the server-sided part which accepts the file and only need the client-sided part? \$\endgroup\$ – Philipp Dec 18 '17 at 13:37
1
\$\begingroup\$

There are multiple ways to get some bytes of text from the client to a server. But one way to do this which should be quite platform-agnostic is with a HTTP POST Request. The Unity class you need for this is the class WWWForm to store the POST data in addition to the class WWW to make the HTTP request.

The example in the official documentation shows you how to take and upload a screenshot, but you can of course use the same technique to upload a string of text. Here is a modification of the example which should do that (untested, but I am feeling lucky):

IEnumerator UploadString() {
    // TODO: replace with the URL of your receiver webservice on your webserver
    string url = "https://example.com/textFileUpload" 

    // TODO: Obtain name and content of the file you want to upload
    string filename = "hello.txt";
    string content = "Hello World!";

    // Create a Web Form
    WWWForm form = new WWWForm();
    form.AddField("fileContent", content);
    form.AddField("fileName", filename);

    // Upload to a cgi script
    WWW w = new WWW(url, form);
    yield return w;
    if (!string.IsNullOrEmpty(w.error)) {
        print(w.error);
    }
    else {
        print("Finished Uploading File");
    }
}

Your server will receive a POST request with the filename in the field fileName and the content in the field fileContent.

What you still need to do is write a server-sided webservice which accepts the HTTP POST request and does something with the received string of text. But this is outside of the scope of this question because it isn't something you would do with Unity. With what technology do you do it instead? There are countless possibilities. ASP.NET, JSP, Perl, Node.JS, PHP, Python + Django, Ruby on Rails... and many more. Pick one and check on Stackoverflow if you need help.

(oh, and keep security in mind. Letting anyone upload anything under any name to a webserver without any plausibility checks is a very bad idea.)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.