<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>
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("失敗奸绷,請(qǐng)重試!");
}
}
},
beforeSubmit : function(arr, $form, options){
},
error: function(data) {
alert("意見反饋失敗,請(qǐng)重試!");
}
};
$("#userForm").ajaxSubmit(option);
return false; //最好返回false,因?yàn)槿绻粹o類型是submit,則表單自己又會(huì)提交一次;返回false阻止表單再次提交
}
main.go
package main
func main() {
http.HandleFunc("/feedBackSubmit", feedBackSubmit) //意見反饋
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal(":8080監(jiān)聽失斞:", err)
}
}
func feedBackSubmit(w http.ResponseWriter, r *http.Request) {
r.ParseMultipartForm(32 << 20)
if r.Method == "GET" {
fmt.Fprintf(w, "InvalidRequest!") //這個(gè)寫入到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)
}
}
}
}