File add API server in Vapor 4


A easy file add server written in Swift

For this straightforward file add tutorial we’ll solely use the Vapor Swift bundle as a dependency. 📦


import PackageDescription

let bundle = Bundle(
    title: "myProject",
    platforms: [
       .macOS(.v10_15)
    ],
    dependencies: [
        .package(url: "https://github.com/vapor/vapor", from: "4.35.0"),
    ],
    targets: [
        .target(
            name: "App",
            dependencies: [
                .product(name: "Vapor", package: "vapor"),
            ],
            swiftSettings: [
                .unsafeFlags(["-cross-module-optimization"], .when(configuration: .launch))
            ]
        ),
        .goal(title: "Run", dependencies: [.target(name: "App")]),
        .testTarget(title: "AppTests", dependencies: [
            .target(name: "App"),
            .product(name: "XCTVapor", package: "vapor"),
        ])
    ]
)

You’ll be able to setup the undertaking with the required recordsdata utilizing the Vapor toolbox, alternatively you possibly can create every thing by hand utilizing the Swift Bundle Supervisor, lengthy story quick, we simply want a starter Vapor undertaking with out further dependencies. Now when you open the Bundle.swift file utilizing Xcode, we will setup our routes by altering the configure.swift file.

import Vapor

public func configure(_ app: Software) throws {

    
    app.middleware.use(FileMiddleware(publicDirectory: app.listing.publicDirectory))

    
    app.routes.defaultMaxBodySize = "10mb"

    
    app.submit("add") { req -> EventLoopFuture<String> in
        let key = strive req.question.get(String.self, at: "key")
        let path = req.utility.listing.publicDirectory + key
        return req.physique.gather()
            .unwrap(or: Abort(.noContent))
            .flatMap { req.fileio.writeFile($0, at: path) }
            .map { key }
    }
}

First we use the FileMiddleware, this may enable us to server recordsdata utilizing the Public listing inside our undertaking folder. If you do not have a listing named Public, please create one, because the file add server will want that. Do not forget to present correct file system permissions if crucial, in any other case we can’t have the ability to write our information contained in the listing. 📁

The following factor that we set is the default most physique measurement. This property can restrict the quantity of knowledge that our server can settle for, you do not actually need to use this technique for big recordsdata as a result of uploaded recordsdata will probably be saved within the system reminiscence earlier than we write them to the disk.

If you wish to add giant recordsdata to the server you need to think about streaming the file as an alternative of gathering the file information from the HTTP physique. The streaming setup would require a bit extra work, but it surely’s not that sophisticated, in case you are desirous about that resolution, you need to learn the Recordsdata API and the physique streaming part utilizing official Vapor docs website.

This time we simply need a lifeless easy file add API endpoint, that collects the incoming information utilizing the HTTP physique right into a byte buffer object, then we merely write this buffer utilizing the fileio to the disk, utilizing the given key from the URL question parameters. If every thing was accomplished with out errors, we will return the important thing for the uploaded file.

File add duties utilizing the URLSession API The Basis frameworks offers us a pleasant API layer for widespread networking duties. We will use the URLSession uploadTask technique to ship a brand new URLRequest with a knowledge object to a given server, however IMHO this API is sort of unusual, as a result of the URLRequest object already has a httpBody property, however you need to explicitly move a “from: Information?” argument while you assemble the duty. However why? 🤔

import Basis

extension URLSession {

    func uploadTask(with request: URLRequest, completionHandler: @escaping (Information?, URLResponse?, Error?) -> Void) -> URLSessionUploadTask {
        uploadTask(with: request, from: request.httpBody, completionHandler: completionHandler)
    }
}

Anyway, I made slightly extension technique, so after I create the URLRequest I can set the httpBody property of it and safely move it earlier than the completion block and use the contents because the from parameter. Very unusual API design alternative from Apple… 🤐

We will put this little snippet right into a easy executable Swift bundle (or after all we will create a complete utility) to check our add server. In our case I will place every thing right into a most important.swift file.

import Basis
import Dispatch

extension URLSession {

    func uploadTask(with request: URLRequest, completionHandler: @escaping (Information?, URLResponse?, Error?) -> Void) -> URLSessionUploadTask {
        uploadTask(with: request, from: request.httpBody, completionHandler: completionHandler)
    }
}


let fileData = strive Information(contentsOf: URL(fileURLWithPath: "/Customers/[user]]/[file].png"))
var request = URLRequest(url: URL(string: "http://localhost:8080/add?key=(UUID().uuidString).png")!)
request.httpMethod = "POST"
request.httpBody = fileData

let activity = URLSession.shared.uploadTask(with: request) { information, response, error in
    guard error == nil else {
        fatalError(error!.localizedDescription)
    }
    guard let response = response as? HTTPURLResponse else {
        fatalError("Invalid response")
    }
    guard response.statusCode == 200 else {
        fatalError("HTTP standing error: (response.statusCode)")
    }
    guard let information = information, let outcome = String(information: information, encoding: .utf8) else {
        fatalError("Invalid or lacking HTTP information")
    }
    print(outcome)
    exit(0)
}

activity.resume()
dispatchMain()

The above instance makes use of the Dispatch framework to attend till the asynchronous file add finishes. You need to change the placement (and the extension) of the file if crucial earlier than you run this script. Since we outlined the add route as a POST endpoint, we’ve got to set the httpMethod property to match this, additionally we retailer the file information within the httpBody variable earlier than we create our activity. The add URL ought to include a key, that the server can use as a reputation for the file. You’ll be able to add extra properties after all or use header values to verify if the person has correct authorization to carry out the add operation. Then we name the add activity extension technique on the shared URLSession property. The good factor about uploadTask is that you may run them on the background if wanted, that is fairly useful if it involves iOS growth. 📱

Contained in the completion handler we’ve got to verify for a number of issues. To start with if there was an error, the add should have failed, so we name the fatalError technique to interrupt execution. If the response was not a legitimate HTTP response, or the standing code was not okay (200) we additionally cease. Lastly we need to retrieve the important thing from the response physique so we verify the information object and convert it to a UTF8 string if attainable. Now we will use the important thing mixed with the area of the server to entry the uploaded file, this time I simply printed out the outcome, however hey, that is only a demo, in an actual world utility you would possibly need to return a JSON response with further information. 😅

Vanilla JavaScript file uploader

Yet another factor… you should utilize Leaf and a few Vanilla JavaScript to add recordsdata utilizing the newly created add endpoint. Really it is very easy to implement a brand new endpoint and render a Leaf template that does the magic. You may want some fundamental HTML and some traces of JS code to submit the contents of the file as an array buffer. It is a fundamental instance.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta title="viewport" content material="width=device-width, initial-scale=1">
    <title>File add</title>
  </head>
  <physique>
      <h1>File add</h1>
      <enter sort="file" id="file" title="file" settle for="picture/*" /><br><br>
      <img id="preview" src="https://theswiftdev.com/photos/logos/brand.png" width="256px">
      <script>
        doc.getElementById('file').addEventListener("change", uploadImage);

        perform uploadImage() {
            var xhr = new XMLHttpRequest();
            xhr.open("POST", "/add?key=take a look at.png", true);
            xhr.onreadystatechange = perform() {
                if(xhr.readyState == 4 && xhr.standing == 200) {
                    doc.getElementById('preview').src = "/" + this.responseText;
                }
            };

            var file = doc.getElementById('file').recordsdata[0];
            if (file) {
                var reader = new FileReader();
                reader.onload = perform() {
                    xhr.ship(reader.outcome);
                }
                reader.readAsArrayBuffer(file);
            }
        }
      </script>
  </physique>
</html>

As you possibly can see it is a normal XHR request mixed with the FileReader JavaScript API. We use the FileReader to transform our enter to a binary information, this fashion our server can write it to the file system within the anticipated format. Generally individuals are utilizing a multipart-encoded type to entry recordsdata on the server, however when you need to work with an API you too can switch uncooked file information. If you wish to be taught extra about XHR requests and AJAX calls, you need to learn my earlier article.

I even have a submit about completely different file add strategies utilizing commonplace HTML kinds and a Vapor 4 server as a backend. I hope you will discover the precise resolution that you simply want to your utility. 👍

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles