一、表单上传:
html客户端部分:
<form action="upload.ashx" method="post" enctype="multipart/form-data"> 选择文件:<input type="file" name="file1" /><br /> <input type="submit" value="上传" /> </form>
一般处理程序服务器端:
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; HttpPostedFile file1 = context.Request.Files["file1"]; helper.uploadFile(file1, "~/upload/");//这里就是对相应方法进行调用 context.Response.Write("ok");//提示执行成功 }
上传代码的封装:
/// <summary> /// 上传图片 /// </summary> /// <param name="file">通过form表达提交的文件</param> /// <param name="virpath">文件要保存的虚拟路径</param> public static void uploadImg(HttpPostedFile file,string virpath) { if (file.ContentLength > 1024 * 1024 * 4) { throw new Exception("文件不能大于4M"); } string imgtype = Path.GetExtension(file.FileName); if(imgtype!=".jpg"&&imgtype!=".jpeg") //图片类型进行限制 { throw new Exception("请上传jpg或JPEG图片"); } using (Image img = Bitmap.FromStream(file.InputStream)) { string savepath = HttpContext.Current.Server.MapPath(virpath+file.FileName); img.Save(savepath); } } /// <summary> /// 上传文件 /// </summary> /// <param name="file">通过form表达提交的文件</param> /// <param name="virpath">文件要保存的虚拟路径</param> public static void uploadFile(HttpPostedFile file, string virpath) { if (file.ContentLength > 1024 * 1024 * 6) { throw new Exception("文件不能大于6M"); } string imgtype = Path.GetExtension(file.FileName); //imgtype对上传的文件进行限制 if (imgtype != ".zip" && imgtype != ".mp3") { throw new Exception("只允许上传zip、rar....文件"); } string dirFullPath= HttpContext.Current.Server.MapPath(virpath); if (!Directory.Exists(dirFullPath))//如果文件夹不存在,则先创建文件夹 { Directory.CreateDirectory(dirFullPath); } file.SaveAs(dirFullPath + file.FileName); }
二、Ajax文件异步上传:
注明:既然有了表单上传为什么又要ajax上传呢?因为表单上传过程中,整个页面就刷新了!ajax异步上传就可以达到只刷新局部位置,下面就简单看看ajax上传吧!
html客户端部分:
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <h2>文件上传</h2> <form action="/api/upload" method="post" enctype="multipart/form-data"> <input type="file" id="file1" /><br /> <input type="button" value="submit" id="submit-button" /> </form> </body> <script src="/static/libs/jquery/jquery-1.11.2.min.js"></script> <script> $("#submit-button").click(function (e) { e.preventDefault(); var formData = new FormData(); formData.append("pic-upload", document.getElementById("file1").files[0]); $.ajax({ type: ‘POST‘, url: "/api/upload", data: formData, //必须false才会自动加上正确的Content-Type contentType: false, // 必须false才会避开jQuery对 formdata 的默认处理,XMLHttpRequest会对 formdata 进行正确的处理 processData: false, success: function (response) { console.log(response); }, error: function (response) { console.log(response); } }); }) </script> </html>
node.js服务器端:
const express = require("express") const fs = require("fs") const mysql = require("mysql") const util = require("util") const { getNow } = require("./tool") const app = express(); var multer = require(‘multer‘);//获得中间件 var upload = multer({dest:‘uploads/‘});//指定配置项,这里指定文件保存于当前目录下的upload子目录 app.use(upload.single(‘pic-upload‘));//运用中间件,并且指明文件名,此名需要同html input name的文件名一致,否则会报错 const bodyParser = require("body-parser"); const { nextTick } = require("process"); app.use("/static/", express.static("./static/")); app.use(‘/node_modules/‘, express.static(‘./node_modules/‘)); app.engine("html", require("express-art-template")) app.use(bodyParser.urlencoded({ extended: false })) app.use(bodyParser.json()) app.get("/upload", (req, res) => { res.render("upload.html"); }) app.post("/api/upload", (req, res) => { // 没有附带文件 res.send(req.file); //服务端响应把客户端获得的文件信息显示在客户端 }) app.get("/404", (req, res) => { res.render("404.html"); }) // 配置一个全局错误处理中间件 app.use(function (err, req, res, next) { res.status(500).json({ err_code: 500, message: err.message }) }) app.listen(5555, () => { console.log("服务启动成功......"); })