php 图片上传及回显,前端用FormData实现文件上传以及图片回显

前端实现文件上传的类型为FormData

先熟悉下FormData的API

var fd=new FormData()//

fd.apend('name','张三');//为fd对象添加参数,以key=>value的键值对的形式

//或者用fd.set('name','张三')

要获取formData中的值,不能直接打印console.log(fd),这样是打印不出来值的,一定要用get()方法才能获取,或者是用数组的方式遍历

例如fd.forEach()方法

fd.get('user');

开始实现文件上传

前端使用标签实现上传

姓名:

其中multiple="multiple" 的参数表示可以选择多张文件上传

手写ajax代码如下

var user = document.getElementById('user');

var file = document.getElementById('foo');

var btn = document.getElementsByTagName('button')[0];

btn.onclick = () => {

var ajx = new XMLHttpRequest();

ajx.open("post", "/upload", true); //设置请求地址和路径

var fd = new FormData();

fd.append('user', user.value);

fd.append('file',file.files[0]);

ajx.onreadystatechange = function () {

if (ajx.readyState == 4 && ajx.status == 200) {

console.log(ajx);

}

}

ajx.send(fd);

}

以上代码要把获取的user的值和文件转换成FormData对象,其中获取文件数据是通过[目标元素].files获取,获取的的值是类似于数组,因为可以是多个文件,所有需要做什么操作可以去遍历一遍,要把表单数据统一转换成FormData对象,可以不用append()方法一项项的去添加,可以利用表单元素的属性进行操作

var fd = new FormData(document.getElementById('form'));

用这种方式每个输入框必须要有name属性,例如

05dbd59895b6

image.png

node配置服务端

上传文件需要安装一个中间件处理express-fileupload

npm install express-fileupload --save

早app.js中注册一下

const fileUpload = require('express-fileupload');

app.use(fileUpload());

手写后台接口路由

var express = require('express');

var router = express.Router();

var path=require('path');

router.post('/upload', function(req, res, next) {

console.log(req.body);

let f = req.files.file;

f.mv(path.join(__dirname,'../public','upload',f.name), function(err) {

if(err){

return res.status(400).send("sdsdsdas");

}

res.send('文件上传成功!');

});

});

module.exports = router;

以上代码 let f = req.files.file;file为前的FormData对象的键值,

如果要上传多个文件,input只需要加multiple="multiple"属性

后台代码

router.post('/upload', function(req, res, next) {

let f = req.files.file;

let newFile =[].concat(f);

newFile.forEach((file,index)=>{

file.mv(path.join(__dirname,'../public','upload',file.name), function(err) {

if(err){

return res.status(400).send("sdsdsdas");

}

});

})

res.send('文件上传成功!');

});

效果如下图所示

05dbd59895b6

截图录屏_选择区域_20201019193413.gif

05dbd59895b6

image.png

上传图片前的图片回显

有时候需要上传图片,选择图片后需要先显示而不是直接取后台返回来的地址

html代码

姓名:

提交

js代码

var form = document.getElementById('form');

var user = document.getElementById('user');

var btn = document.getElementsByTagName('button')[0];

var file = document.getElementById('foo');

var showImg = document.getElementsByClassName('image')[0];

file.onchange = (e) => {

const reader = new FileReader();

reader.readAsDataURL(file.files[0]);

var img = new Image();

reader.onloadend = (e) => {

img.src = reader.result;

showImg.appendChild(img);

}

}

btn.onclick = () => {

var ajx = new XMLHttpRequest();

ajx.open("post", "/upload", true);

var fd = new FormData(form);

ajx.onreadystatechange = function () {

if (ajx.readyState == 4 && ajx.status == 200) {

console.log(ajx);

}

}

ajx.send(fd);

}

其中的onChange方法是input标签选择图片时触发,此时需要知道FileReader对象的用法以及API

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
后端代码实现: 1.引入相关依赖 ```xml <!-- 文件 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency> ``` 2.配置文件相关信息 ```yaml # 文件限制 spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB spring.servlet.multipart.enabled=true ``` 3.编写文件接口 ```java @RestController @RequestMapping("/api/file") public class FileController { @PostMapping("/upload") public String upload(@RequestParam("file") MultipartFile file) throws IOException { if (file.isEmpty()) { return "文件为空"; } String fileName = file.getOriginalFilename(); String filePath = "D:\\temp\\"; File dest = new File(filePath + fileName); file.transferTo(dest); return "上成功"; } } ``` 前端代码实现: 1.安装 axios 和 element-ui ```bash npm install axios element-ui --save ``` 2.编写文件组件 ```vue <template> <div> <el-upload class="upload-demo" action="/api/file/upload" :auto-upload="false" :on-change="handleChange" > <el-button slot="trigger" type="primary">选取文件</el-button> <el-button v-if="imageUrl" type="success" @click="handleUpload">上到服务器</el-button> <div class="el-upload__tip" slot="tip">只能上jpg/png文件,且不超过10MB</div> </el-upload> <img v-if="imageUrl" :src="imageUrl" style="max-width: 100%;"> </div> </template> <script> import axios from 'axios'; import { Message } from 'element-ui'; export default { data() { return { imageUrl: '', file: null, }; }, methods: { handleChange(file) { this.file = file.raw; this.imageUrl = URL.createObjectURL(this.file); }, handleUpload() { const formData = new FormData(); formData.append('file', this.file); axios.post('/api/file/upload', formData, { headers: { 'Content-Type': 'multipart/form-data', }, }).then(() => { Message.success('上成功'); }).catch(() => { Message.error('上失败'); }); }, }, }; </script> ``` 至此,图片回显的代码实现就完成了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值