html5原生js拖拽上传(golang版)
一次只能传一个文件,需在main.go同级目录中建一个upload文件夹
main.go
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部分参考:https://blog.csdn.net/nanfang1105/article/details/77965915
如需跨域,可参考:https://blog.csdn.net/benben_2015/article/details/79247024