前言
大家都知道,早期的XMLHttpRequest不支持文件上传,一般用第三方js插件或者flash,现在可以借助XMLHttpRequest Level 2 的FormData对象实现二进制文件上传,正好最近工作中遇到了这个需求,所以本文就来给大家总结下实现的方法,话不多说了,来一起看看详细的介绍吧。
示例代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
@ extends ( 'layouts.art' ) @section( 'content' ) <form class = "form-horizontal" id= "avatar" > {{ csrf_field() }} <div class = "form-group" > <label for = "inputEmail3" class = "col-sm-2 control-label" >名字</label> <div class = "col-sm-8" > <input type= "title" class = "form-control" id= "title" name= "title" > </div> </div> <div class = "form-group" > <label for = "inputEmail3" class = "col-sm-2 control-label" >头像</label> <div class = "col-sm-8" > <input type= "file" class = "form-control" id= "title" name= "photo" > </div> </div> <div class = "form-group" > <div class = "col-sm-offset-2 col-sm-10" > <a class = "btn btn-default" onclick= "uploadInfo()" >上传</a> </div> </div> </form> <script src= "https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js" ></script> <script type= "text/javascript" > function uploadInfo() { var formData = new FormData($( "#avatar" )); $.ajax({ url: "{{url('photo')}}" , type: 'POST' , data: formData, contentType: false, processData: false, success: function (returndata) { console.log(returndata); }, error: function (returndata) { console.log(returndata); } }); } </script> @endsection |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
//生成路径,图片存储 $ext = $request ->photo->getClientOriginalExtension(); $cover_path = "images/album/covers/" . time() . $ext ; $name = "photo" .time(); $src = "images/album/photos/" . $name . ".jpg" ; Image::make( $request ->photo)->save(public_path( $src ));*/ //批量上传图片 foreach ( $request ->photo as $key => $value ) { //生成路径,图片存储 $prefix = "photo" .mt_rand(1,1000); $Origname = $value ->getClientOriginalName(); $name = $prefix . $Origname ; $src = "images/album/photos/" . $name ; $realPath = $value ->getRealPath(); Storage::disk( 'uploads' )->put( $src , file_get_contents ( $realPath )); } |
更多参考
https://developer.mozilla.org/zh-CN/docs/Web/API/FormData/UsingFormDataObjects
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对服务器之家的支持。
原文链接:https://fjun.org/laravel-ajax/