wide/file/importer.go

78 lines
1.7 KiB
Go
Raw Permalink Normal View History

2015-01-18 08:59:10 +03:00
// Copyright (c) 2014-2015, b3log.org
2015-01-01 05:06:33 +03:00
//
2014-12-20 15:39:45 +03:00
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
2015-01-01 05:06:33 +03:00
//
2014-12-20 15:39:45 +03:00
// http://www.apache.org/licenses/LICENSE-2.0
2015-01-01 05:06:33 +03:00
//
2014-12-20 15:39:45 +03:00
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
2014-11-28 18:12:38 +03:00
package file
import (
"io"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"github.com/b3log/wide/util"
)
2014-12-07 06:29:45 +03:00
type fileInfo struct {
2014-11-28 18:12:38 +03:00
Name string `json:"name"`
Type string `json:"type"`
Error string `json:"error,omitempty"`
}
2014-12-07 06:29:45 +03:00
func handleUpload(p *multipart.Part, dir string) (fi *fileInfo) {
fi = &fileInfo{
2014-11-28 18:12:38 +03:00
Name: p.FileName(),
Type: p.Header.Get("Content-Type"),
}
path := filepath.Clean(dir + "/" + fi.Name)
f, _ := os.Create(path)
io.Copy(f, p)
f.Close()
return
}
2014-12-07 06:29:45 +03:00
func handleUploads(r *http.Request, dir string) (fileInfos []*fileInfo) {
fileInfos = make([]*fileInfo, 0)
2014-11-28 18:12:38 +03:00
mr, err := r.MultipartReader()
part, err := mr.NextPart()
for err == nil {
if name := part.FormName(); name != "" {
if part.FileName() != "" {
fileInfos = append(fileInfos, handleUpload(part, dir))
}
}
part, err = mr.NextPart()
}
return
}
// Upload handles request of file upload.
func Upload(w http.ResponseWriter, r *http.Request) {
data := map[string]interface{}{"succ": true}
defer util.RetJSON(w, r, data)
q := r.URL.Query()
dir := q["path"][0]
data["files"] = handleUploads(r, dir)
}