iris部分
package main
import (
"fmt"
"io"
"net/http"
"os"
)
func uploadHandler_video(w http.ResponseWriter, r *http.Request) {
err := r.ParseMultipartForm(10 << 20)
if err != nil {
fmt.Println("Error parsing the form")
return
}
file, handler, err := r.FormFile("file")
if err != nil {
fmt.Println("Error retrieving the file")
return
}
defer file.Close()
f, err := os.OpenFile("./assets/video/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Println("Error creating the file")
return
}
defer f.Close()
io.Copy(f, file)
fmt.Fprintf(w, "File uploaded successfully")
}
func uploadHandler_images(w http.ResponseWriter, r *http.Request) {
err := r.ParseMultipartForm(10 << 20)
if err != nil {
fmt.Println("Error parsing the form")
return
}
file, handler, err := r.FormFile("file")
if err != nil {
fmt.Println("Error retrieving the file")
return
}
defer file.Close()
f, err := os.OpenFile("./assets/images/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Println("Error creating the file")
return
}
defer f.Close()
io.Copy(f, file)
fmt.Fprintf(w, "File uploaded successfully")
}
func main() {
http.HandleFunc("/upload-video", uploadHandler_video)
http.HandleFunc("/upload-image",uploadHandler_images)
http.ListenAndServe(":8091", nil)
}
vue部分
<script setup>
const changeUploadBtn = async() => {
const fileHandle = await window.showOpenFilePicker({
excludeAcceptAllOption: false,
types: [
{
description: '视频文件',
accept: {
'video/*': ['.mp4', '.avi', '.mov']
},
},
],
});
const file = await fileHandle[0].getFile();
console.log(file)
const formData = new FormData();
formData.append('file', file);
await fetch('http://localhost:8091/upload-video', {
method: 'POST',
body: formData
});
}
const uploadFMImageBtn = async() => {
const fileHandle = await window.showOpenFilePicker({
excludeAcceptAllOption: false,
types: [
{
description: '图片文件',
accept: {
'image/*': ['.png', '.gif', '.jpeg', '.jpg', '.webp']
},
},
],
});
const file = await fileHandle[0].getFile();
console.log(file)
const formData = new FormData();
formData.append('file', file);
await fetch('http://localhost:8091/upload-image', {
method: 'POST',
body: formData
});
}
script>
<template>
<div>
<button @click="changeUploadBtn">上传视频button>
<button @click="uploadFMImageBtn ">上传图片button>
div>
template>
<style scoped>
style>
效果如图
