- html代码
<form id="userForm" action="" enctype="multipart/form-data" method="post">
<input id="imgInput" type="file" name="imgInput" accept="image/*" multiple/>
<input " type="button" value="提交" onclick="ajaxSubmitForm();" />
</form>
- js代码
function ajaxSubmitForm() {
var option = {
url : '/feedBackSubmit',
type : 'POST',
dataType : 'json',
success : function(data) {
if (data.code == 1) {//成功
if (data.content != "") {
alert(data.content);
} else {
alert("成功!");
}
} else {//失败
if (data.content != "") {
alert(data.content);
} else {
alert("失败,请重试!");
}
}
},
beforeSubmit : function(arr, $form, options){
},
error: function(data) {
alert("意见反馈失败,请重试!");
}
};
$("#userForm").ajaxSubmit(option);
return false; //最好返回false,因为如果按钮类型是submit,则表单自己又会提交一次;返回false阻止表单再次提交
}
- golang代码
main.go
package main
func main() {
http.HandleFunc("/feedBackSubmit", feedBackSubmit) //意见反馈
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal(":8080监听失败:", err)
}
}
func feedBackSubmit(w http.ResponseWriter, r *http.Request) {
r.ParseMultipartForm(32 << 20)
if r.Method == "GET" {
fmt.Fprintf(w, "InvalidRequest!") //这个写入到w的是输出到客户端的
return
} else if r.Method == "POST"
files := r.MultipartForm.File["imgInput"]
var fileNamePath = ""
if files != nil {
l := len(files)
for i := 0; i < l; i++ {
file, err := files[i].Open()
defer file.Close()
if err != nil {
log.Println(err)
}
s1 := strings.Split(files[i].Filename, ".")
fielType := s1[len(s1)-1]
newFileName := TimeUUID().String() + "." + fielType
cur, err := os.Create(Common.GetParentDirectory() + "/support/" + newFileName)
defer cur.Close()
if err != nil {
log.Println(err)
} else {
if i == 0 {
fileNamePath = Common.GetParentDirectory() + "/support/" + newFileName
} else {
fileNamePath = fileNamePath + "," + Common.GetParentDirectory() + "/support/" + newFileName
}
}
io.Copy(cur, file)
}
}
}
}
有疑问加站长微信联系(非本文作者)