Set up a local server with Go-File upload-

at first

Set up a Web Server with Go and upload files from the Android application

environment

PC Windows10 Android Studio 4.0 Kotlin 1.3.72 Android device Emulator (API Level 29) Go 1.11.1

Diagram

go_server.png Send a file from the Android app, save it on the server side, and return the status code from the server to the app

Implementation

Local server

Server.go


package controllers

import (
	"fmt"
	"net/http"
	"io/ioutil"
	"os"
)

func apiSampleHandler(w http.ResponseWriter, r *http.Request) {
	switch(r.Method) {
		case "POST":
			fmt.Println("POST")
            //Get uploaded files and headers
			file, fileHeader, _ := r.FormFile ("upload_file") 
			fileName := fileHeader.Filename //Get the filename from the header
			defer file.Close()              //Close the file at the end
			data, _ := ioutil.ReadAll(file) //Read file
			saveFile, _ := os.Create(fileName) //Generate a file for saving
			defer saveFile.Close()          //Close the file for saving at the end
			_, err = saveFile.Write(data)   //Write to file
			if err != nil {
				fmt.Println("can not write file")
				w.WriteHeader(http.StatusBadRequest)
				return
			}
		case "GET":
			fmt.Println("GET")
	}
    // 200:Returns OK
	w.WriteHeader(http.StatusOK)
}

// main.Call from go to start the server
func StartWebServer() error {
	http.HandleFunc("/", apiSampleHandler)
	return http.ListenAndServe(":8080", nil)
}

Run main.go and start the server Go to http: // localhost: 8080 and make sure the server is up

Android app

1.Androidmanifest.xml

Define Permission to access the Internet

AndroidManifest.xml


<uses-permission android:name="android.permission.INTERNET" />

Since the http communication setting is turned off from Android 9.0, set uses CleartextTrafic to true

AndroidManifest.xml


<application
abridgement
    android:usesCleartextTraffic="true">
    <activity android:name=".MainActivity">
abridgement
    </activity>
</application>
  1. Generate file

Generate a text file in the application-specific area of the Android device (under `` `/ data / data / {package_name} / files```)

File.kt


const val FILE_EXPAND = ".txt"

class File {
    fun makeTxtFile(context: Context, fileName: String, str: String) {
        try {
            context.openFileOutput(fileName + FILE_EXPAND, Context.MODE_PRIVATE).use {
                it.write(str.toByteArray())
            }
        } catch (e: IOException) {
            Log.e("File", "#makeTxtFile $e")
        }
    }
}

Confirm file generation View files on the device with Device File Explorer (https://developer.android.com/studio/debug/device-file-explorer?hl=ja )

    1. Server access

Read the file and send the file via http communication

Net.kt


 fun startConnection(context: Context, requestUrl: String, requestMethod: String, fileName: String): Pair<Int, String> {
        val url = URL(requestUrl)                      //URL object generation
        //UrlConnection object creation
        val urlConnection = url.openConnection() as HttpURLConnection 
        var result = ""
        var responseCode = 0
        try {
            val boundary = "--------------------------" 
            urlConnection.requestMethod = requestMethod // POST,GET etc.
            urlConnection.doOutput = true               //Send request body
            urlConnection.doInput = true                //Reception of response body
            urlConnection.useCaches = false             //Use of cache
            // multipart/form-data: Send multiple data, boundary: Separation between multiple data
            urlConnection.setRequestProperty(
                "Content-Type",
                "multipart/form-data; boundary=$boundary" 
            )
            val filePath = context.filesDir             //App-specific area path
            val file = File("$filePath/$fileName$FILE_EXPAND") //Create a file object
            FileInputStream(file).use { fileInputStream ->
                urlConnection.connect()                 //Establish a connection
                DataOutputStream(urlConnection.outputStream).use {
                   it.writeBytes(                       //Set header
                       TWO_HYPHEN + boundary + LINE_END +
                               "Content-Disposition: form-data; name=\"upload_file\"; " +
                               "filename=\"$fileName$FILE_EXPAND\"$LINE_END" +
                               "Content-Type: application/octet-stream$LINE_END$LINE_END"
                   )
                   //File writing
                   val buffer = ByteArray(BUFFER_SIZE)
                   var bytesRead: Int
                   do {
                       bytesRead = fileInputStream.read(buffer)
                       if (bytesRead == -1) break
                       it.write(buffer, 0, bytesRead)
                   } while (true)
                   it.writeBytes(                       //footer settings
                        LINE_END + TWO_HYPHEN + boundary + TWO_HYPHEN + LINE_END
                   )
                   it.flush()
                }
            }
            responseCode = urlConnection.responseCode   //Get response code
 
            BufferedReader(InputStreamReader(urlConnection.inputStream)).use {
                val sb = StringBuffer()
                for (line in it.readLines()) {
                    line.let { sb.append(line) }
                }
                result = sb.toString()
            }
        } catch (e: Exception) {
            Log.e("Net", "#startConnection$e")
        } finally {
            urlConnection.disconnect()
        }
        return responseCode to result
    }
}

Four. Confirmation of IP address

Confirm the IP address of the server (PC) you want to access by executing the following with the command prompt

>ipconfig

Five. Connect your PC and Android device to the same network environment

  1. Connect with Android

Set http: // {confirmed IP address}: 8080 in requestUrl of Net # startConnection and execute the application

Confirm file upload

Check the same directory as main.go on your PC Complete if the file has been created

Finally

The whole source is here The access destination, RequestMethod, and file name can be changed dynamically by the application.

References

Go server side

File upload in Go language

Android application side

[Android] Save files in the app FileOutputStream, FileInputStream Upload File To Server - Android Example [Android] while-FileInputStream.read error in kotlin [Kotlin] I want to return multiple values!

Recommended Posts

Set up a local server with Go-File upload-
Set up a local server with Go-File download-
Set up a Samba server with Docker
Set up a simple HTTPS server with asyncio
How to set up a local development server
Set up a simple local server on your Mac
[Vagrant] Set up a simple API server with python
Set up a web server with CentOS7 + Anaconda + Django + Apache
Set up a mail server using Twisted
Set up a simple HTTPS server in Python 3
Build a local server with a single command [Mac]
Send mail with mailx to a dummy SMTP server set up with python.
Set up a test SMTP server in Python.
Set up a UDP server in C language
Set up a local web server in 30 seconds using python 3's http.server
Set up a simple SMTP server in Python
Local server with python
Set up a Minecraft resource (Spigot) server via docker (2)
Set up a file server on Ubuntu 20.04 using Samba
Set up a free server on AWS in 30 minutes
[Part 1] Let's set up a Minecraft server on Linux
Set up a Minecraft resource (Spigot) server via docker
Set up a Python development environment with Sublime Text 2
Set up a Python development environment with Visual Studio Code
Reload the server set up with gunicorn when changing the code
Set up social login with Django
Set up pygit2 with static link
Creating a Flask server with Docker
Set up Ubuntu as a Linux cheat sheet and https server
Set up a Lambda function and let it work with S3 events!
Get a local DynamoDB environment with Docker
Draw a Mandelbrot set with Brainf * ck
Set up reverse proxy to https server with CentOS Linux 8 + Apache mod_ssl
Introduction and usage of Python bottle ・ Try to set up a simple web server with login function
Set up a server that processes multiple connections at the same time
Rock-paper-scissors with Python Let's run on a Windows local server for beginners
When I connect to a remote Jupyter Server with VScode, it's remote but local
[Python] How to create a local web server environment with SimpleHTTPServer and CGIHTTPServer
Start a temporary http server locally with Pytest
Install Windows 10 from a Linux server with PXE
Set up golang with goenv on GNU / Linux
Start a simple Python web server with Docker
Pretend to be a server with two PCs
Launch a web server with Python and Flask
Set up a Python development environment on Marvericks
Mount a directory on another server with sshfs
Create a "Hello World" (HTTP) server with Tornado
How to set up a Google Colab environment with Coursera's advanced machine learning courses
Build a server on Linux and local network with Raspberry Pi NextCloud and desktop sharing
I want to set up a mock server for python-flask in seconds using swagger-codegen.
Set up a file server using samba on ZeroPi of Friendly Arm [Purchased Items]
Set up a file server using samba on ZeroPi of Friendly Arm [Personal import]
Create an animated GIF local server with Python + Flask
Set up a development environment for natural language processing
How to set up a Python environment using pyenv
I made a ready-to-use syslog server with Play with Docker
A story that struggled with the common set HTTP_PROXY = ~
Set up Docker on Oracle Linux (7.x) with Vagrant
A server that echoes data POSTed with flask / python
Create a home music server with Centos8 + Universal Media Server
[Python] I tried running a local server using flask