一次只能傳一個文件,需在main.go同級目錄中建一個upload文件夾javascript
main.gohtml
package main import ( "fmt" "io" "net/http" "os" ) const ( upload_path string = "./upload/" ) //上傳 func uploadHandle(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { io.WriteString(w, tpl) } else { //獲取文件內容 要這樣獲取 file, head, err := r.FormFile("upfile") fmt.Println(file) if err != nil { fmt.Println(err) return } defer file.Close() //建立文件 fW, err := os.Create(upload_path + head.Filename) if err != nil { fmt.Println("文件建立失敗") return } defer fW.Close() _, err = io.Copy(fW, file) if err != nil { fmt.Println("文件保存失敗") return } fmt.Println(w, head.Filename+" 保存成功") //io.WriteString(w, head.Filename+" 保存成功") //http.Redirect(w, r, "/success", http.StatusFound) //io.WriteString(w, head.Filename) } } func main() { fmt.Println("OK!請訪問 :8080/upload") //啓動一個http 服務器 http.HandleFunc("/upload", uploadHandle) err := http.ListenAndServe(":8080", nil) if err != nil { fmt.Println("服務器啓動失敗") return } } var tpl = `<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>drag file</title> </head> <body> <div class="container"> <div id="fileSpan" style="background-color:red;width:200px;height:200px"></div> </div> <script type="text/javascript"> window.onload = function(){ var uuz = document.getElementById('fileSpan'); uuz.ondragenter = function(e){ e.preventDefault(); } uuz.ondragover = function(e){ e.preventDefault(); this.innerHTML = '請鬆開'; } uuz.ondragleave = function(e){ e.preventDefault(); this.innerHTML = '請拖入要上傳的文件'; } uuz.ondrop = function(e){ e.preventDefault(); var upfile = e.dataTransfer.files[0]; //獲取要上傳的文件對象(能夠上傳多個) alert(upfile.name) alert(upfile.type) var formdata = new FormData(); var xhr = new XMLHttpRequest(); formdata.append('upfile', upfile); //設置服務器端接收的name爲upfile xhr.open("post","upload"); xhr.onreadystatechange = function(){ if(this.readyState==4){ if(this.status==200){ //上傳成功 var resultText = this.responseText; console.info(resultText); //轉json var jsonObj = JSON.parse(resultText); console.info(jsonObj); if(jsonObj.success){ //生成input表單 var fileId = createInput(jsonObj.uuid); //生成顯示名稱 appendFile1(fileId,upfile.name); } }else{ alert('上傳失敗,請使用另外一種方式上傳'); } } } xhr.send(formdata); } } </script> </body> </html>`
html部分參考:http://www.javashuo.com/article/p-hgsxvmku-cp.htmljava
如需跨域,可參考:http://www.javashuo.com/article/p-runzwcmv-mc.htmljson