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上传吧!
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.set({
'content-type': 'application/json; charset=utf-8'
});
res.end("上传成功!");
})
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("服务启动成功......");
})
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- igbc.cn 版权所有 湘ICP备2023023988号-5
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务