This is the part 1 of 2 in DropzoneJS + Go series.
DropzoneJS is an open source library that provides drag'n'drop file uploads with image previews. It is a great JavaScript library which actually does not even rely on JQuery. In this tutorial, we are building a multiple file upload form using DropzoneJS, and the backend will be handled by Go and Iris.
go get -u github.com/kataras/iris
Your folder&file structure should look like this after the preparation:
Open file "./views/upload.html" and let us create a DropzoneJs form.
Copy the content below to "./views/upload.html" and we will go through each line of code individually.
<!-- /views/upload.html -->
<html>
<head>
<title>DropzoneJS Uploader</title>
<!-- 1 -->
<link href="/public/css/dropzone.css" type="text/css" rel="stylesheet" />
<!-- 2 -->
<script src="/public/js/dropzone.js"></script>
</head>
<body>
<!-- 3 -->
<form action="/upload" method="POST" class="dropzone" id="my-dropzone">
<div class="fallback">
<input name="file" type="file" multiple />
<input type="submit" value="Upload" />
</div>
</form>
</body>
</html>
Now you have come to Last part of the tutorial. In this section, we will store files sent from DropzoneJS to the "./public/uploads" folder.
Open "main.go" and copy the code below:
// main.go
package main
import (
"os"
"io"
"strings"
"github.com/kataras/iris"
)
const uploadsDir = "./public/uploads/"
func main() {
app := iris.New()
// Register templates
app.RegisterView(iris.HTML("./views", ".html"))
// Make the /public route path to statically serve the ./public/... contents
app.StaticWeb("/public", "./public")
// Render the actual form
// GET: http://localhost:8080
app.Get("/", func(ctx iris.Context) {
ctx.View("upload.html")
})
// Upload the file to the server
// POST: http://localhost:8080/upload
app.Post("/upload", iris.LimitRequestBodySize(10<<20), func(ctx iris.Context) {
// Get the file from the dropzone request
file, info, err := ctx.FormFile("file")
if err != nil {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.Application().Logger().Warnf("Error while uploading: %v", err.Error())
return
}
defer file.Close()
fname := info.Filename
// Create a file with the same name
// assuming that you have a folder named 'uploads'
out, err := os.OpenFile(uploadsDir+fname,
os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.Application().Logger().Warnf("Error while preparing the new file: %v", err.Error())
return
}
defer out.Close()
io.Copy(out, file)
})
// Start the server at http://localhost:8080
app.Run(iris.Addr(":8080"))
}
Open the terminal at the current project's folder and execute:
$ go run main.go
Now listening on: http://localhost:8080
Application started. Press CTRL+C to shut down.
Now go to browser, and navigate to http://localhost:8080, you should be able to see a page as below:
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。