mirror of
https://github.com/kataras/iris.git
synced 2025-02-02 15:30:36 +01:00
add a test example for upload files as requested at: #1516
Former-commit-id: afb2d3e9c0902cce6c46d26b5b6cfc51551c2373
This commit is contained in:
parent
9b172fe4ab
commit
fb4dcf3134
|
@ -15,8 +15,13 @@ import (
|
|||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app := newApp()
|
||||
// start the server at http://localhost:8080 with post limit at 32 MB.
|
||||
app.Listen(":8080", iris.WithPostMaxMemory(32<<20 /* same as 32 * iris.MB */))
|
||||
}
|
||||
|
||||
func newApp() *iris.Application {
|
||||
app := iris.New()
|
||||
app.RegisterView(iris.HTML("./templates", ".html"))
|
||||
|
||||
// Serve the upload_form.html to the client.
|
||||
|
@ -39,7 +44,7 @@ func main() {
|
|||
// uploads any number of incoming files ("multiple" property on the form input).
|
||||
//
|
||||
|
||||
// second argument is totally optionally,
|
||||
// second argument is optional,
|
||||
// it can be used to change a file's name based on the request,
|
||||
// at this example we will showcase how to use it
|
||||
// by prefixing the uploaded file with the current user's ip.
|
||||
|
@ -70,8 +75,7 @@ func main() {
|
|||
ctx.Writef("%d files uploaded", len(files)-failures)
|
||||
})
|
||||
|
||||
// start the server at http://localhost:8080 with post limit at 32 MB.
|
||||
app.Listen(":8080", iris.WithPostMaxMemory(32<<20))
|
||||
return app
|
||||
}
|
||||
|
||||
func saveUploadedFile(fh *multipart.FileHeader, destDirectory string) (int64, error) {
|
||||
|
@ -104,5 +108,9 @@ func beforeSave(ctx iris.Context, file *multipart.FileHeader) {
|
|||
// prefix the Filename with the $IP-
|
||||
// no need for more actions, internal uploader will use this
|
||||
// name to save the file into the "./uploads" folder.
|
||||
if ip == "" {
|
||||
return
|
||||
}
|
||||
|
||||
file.Filename = ip + "-" + file.Filename
|
||||
}
|
||||
|
|
32
_examples/http_request/upload-files/main_test.go
Normal file
32
_examples/http_request/upload-files/main_test.go
Normal file
|
@ -0,0 +1,32 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/kataras/iris/v12/httptest"
|
||||
)
|
||||
|
||||
func TestUploadFiles(t *testing.T) {
|
||||
app := newApp()
|
||||
e := httptest.New(t, app)
|
||||
|
||||
// upload the file itself.
|
||||
fh, err := os.Open("main.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer fh.Close()
|
||||
|
||||
e.POST("/upload").WithMultipart().WithFile("files", "main.go", fh).
|
||||
Expect().Status(http.StatusOK)
|
||||
|
||||
f, err := os.Open("uploads/main.go")
|
||||
if err != nil {
|
||||
t.Fatalf("expected file to get actually uploaded on the system directory but: %v", err)
|
||||
}
|
||||
f.Close()
|
||||
|
||||
os.Remove(f.Name())
|
||||
}
|
Loading…
Reference in New Issue
Block a user