<!DOCTYPE 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>
<form enctype="multipart/form-data" id="form1" method="post" action="">
文件: <input type="file" name="imgfile" id="upfile">
<input type="button" id="upimage" value="图片上传1">
<div id="ln">tu</div><br>
<input type="text" name="im1" id="im1" value="" />
<input type="text" />
</form>
</body>
</html>
<script type="text/javascript" src="javascripts/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="javascripts/jQuery.form.js"></script>
<script>
$(function() {
$("#upimage").bind("click", function() {
if ($("#upfile").val() == "") {
alert("请选择一个图片文件,再点击");
return;
} else {
$("#form1").ajaxSubmit({
url: "/uploader",
type: "POST",
success: function(response) {
$("#ln").html("<img src='" + response.newPath + "' width='100' height='60'/>");
$("#im1").val(response.newPath);
},
error: function(msg) {
alert("出错了");
}
});
}
})
});
</script>
var express = require('express');
var formidable = require('formidable');
var fs = require('fs');
var router = express.Router();
router.post('/', function(req, res, next) {
var form = new formidable.IncomingForm();
//创建上传表单
form.encoding = 'utf-8';
//设置编辑
form.uploadDir = 'public/upload/';
//设置上传目录
form.keepExtensions = true;
//保留后缀
form.maxFieldsSize = 2 * 1024 * 1024;
//文件大小
form.parse(req, function(err, fields, files) {
if (!err) {
var imgFileName = "/upload/" + Date.parse(new Date()) + ".jpg";
//文件名(用随机数,最好用当前时间) //图片写入地址;
var newPath = "public" + imgFileName;
//重命名
console.log("newPath", newPath);
fs.renameSync(files.imgfile.path, newPath);
res.json({ "newPath": imgFileName });
}
console.log(files);
})
});
module.exports = router;
formidable接收图片
最新推荐文章于 2022-04-26 16:41:16 发布
这篇博客展示了如何使用HTML、jQuery和Ajax实现图片上传功能,并通过Node.js后端利用formidable模块处理上传请求。用户选择图片后,前端会通过Ajax将文件发送到服务器,服务器接收到文件后进行保存并返回新路径,前端则更新图片显示和输入框的值。

1625

被折叠的 条评论
为什么被折叠?



