wide/file/exporter.go

90 lines
1.9 KiB
Go
Raw Normal View History

2014-11-24 12:24:35 +03:00
// Copyright (c) 2014, B3log
2014-11-28 18:12:38 +03:00
//
2014-11-24 12:24:35 +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
2014-11-28 18:12:38 +03:00
//
2014-11-24 12:24:35 +03:00
// http://www.apache.org/licenses/LICENSE-2.0
2014-11-28 18:12:38 +03:00
//
2014-11-24 12:24:35 +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-24 05:39:33 +03:00
package file
import (
"encoding/json"
"net/http"
2014-11-24 12:20:43 +03:00
"os"
2014-11-24 05:39:33 +03:00
"path/filepath"
"github.com/b3log/wide/util"
)
2014-11-24 06:17:42 +03:00
// GetZip handles request of retrieving zip file.
func GetZip(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
path := q["path"][0]
if ".zip" != filepath.Ext(path) {
http.Error(w, "Bad Request", 400)
return
}
if !util.File.IsExist(path) {
http.Error(w, "Not Found", 404)
return
}
2014-11-24 12:20:43 +03:00
filename := filepath.Base(path)
w.Header().Set("Content-Disposition", "attachment; filename="+filename)
2014-11-24 06:17:42 +03:00
w.Header().Set("Content-type", "application/zip")
http.ServeFile(w, r, path)
2014-11-24 12:20:43 +03:00
os.Remove(path)
2014-11-24 06:17:42 +03:00
}
2014-11-24 05:39:33 +03:00
// CreateZip handles request of creating zip.
func CreateZip(w http.ResponseWriter, r *http.Request) {
data := map[string]interface{}{"succ": true}
defer util.RetJSON(w, r, data)
var args map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
2014-12-13 13:47:41 +03:00
logger.Error(err)
2014-11-24 05:39:33 +03:00
data["succ"] = false
return
}
path := args["path"].(string)
base := filepath.Base(path)
if !util.File.IsExist(path) {
data["succ"] = false
data["msg"] = "Can't find file [" + path + "]"
return
}
zipFile, err := util.Zip.Create(path + ".zip")
if nil != err {
2014-12-13 13:47:41 +03:00
logger.Error(err)
2014-11-24 05:39:33 +03:00
data["succ"] = false
return
}
defer zipFile.Close()
if util.File.IsDir(path) {
zipFile.AddDirectory(base, path)
} else {
zipFile.AddEntry(base, path)
}
}