惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

N
News and Events Feed by Topic
D
Docker
云风的 BLOG
云风的 BLOG
F
Fortinet All Blogs
F
Full Disclosure
H
Hackread – Cybersecurity News, Data Breaches, AI and More
P
Proofpoint News Feed
Microsoft Azure Blog
Microsoft Azure Blog
WordPress大学
WordPress大学
The GitHub Blog
The GitHub Blog
L
LangChain Blog
H
Help Net Security
B
Blog
T
Tailwind CSS Blog
V
V2EX
博客园_首页
阮一峰的网络日志
阮一峰的网络日志
人人都是产品经理
人人都是产品经理
The Cloudflare Blog
Recent Announcements
Recent Announcements
aimingoo的专栏
aimingoo的专栏
美团技术团队
A
About on SuperTechFans
C
Cybersecurity and Infrastructure Security Agency CISA
K
Kaspersky official blog
I
InfoQ
Project Zero
Project Zero
I
Intezer
Google DeepMind News
Google DeepMind News
博客园 - 【当耐特】
Hugging Face - Blog
Hugging Face - Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
T
Threat Research - Cisco Blogs
Last Week in AI
Last Week in AI
C
Cyber Attacks, Cyber Crime and Cyber Security
G
GRAHAM CLULEY
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
AWS News Blog
AWS News Blog
Spread Privacy
Spread Privacy
S
Securelist
Recorded Future
Recorded Future
D
Darknet – Hacking Tools, Hacker News & Cyber Security
博客园 - 叶小钗
S
Security Affairs
Blog — PlanetScale
Blog — PlanetScale
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
月光博客
月光博客
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
罗磊的独立博客
The Hacker News
The Hacker News

Giscafer's blog

博客停更说明 使用 ViewContainerRef 探索Angular DOM操作 GIS520论坛关闭停止运营 ionic3之组件封装篇 ionic3之图片选择插件com.synconset.imagepicker ionic3开发遇到的一些问题及解决方法 ionic3之自定义tabs菜单图标 ionic3 之Android的actionsheet渲染和ios一致 Hexo博客畅言评论插件试用 从GISer到互联网前端工程师,JUST DO IT Cafe主题v1.0发布 React搭建百度前端技术学院习题演示SPA react-ponitor React 与 Redux 实践 —— 城市筛选面板 1.Two Sum 如何组件化开发WebGIS系统 2016年末总结 代码理解React组件生命周期过程 hexo-theme-cafe
angular实现IM聊天图片发送
2017-05-07 · via Giscafer's blog

IM聊天图片发送有两种方式

  • 截图粘贴到信息框后点击发送
  • 选择本地图片发送

图片剪切粘贴,使用QQ或者其他平台的截图功能,截图后粘贴Ctrl+V,这个过程需要获取粘贴板上的图片数据,并在页面中展示,也就是将图片数据创建一个img元素,就可以显示出来了。

从粘贴面板中获取图片数据

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

* 黏贴发送图片

* @param e

*/

pasteData(e) {

e.preventDefault();

let clipboardData = e.clipboardData;

if (clipboardData) {

let items = clipboardData.items;

if (!items) {

return;

}

let item;

let types = clipboardData.types || [];

for (let i = 0, len = types.length; i< len; i++) {

if (types[i] === 'Files') {

item = items[i];

break;

}

}

if (item && item.kind === 'file' && item.type.match(/^image\//i)) {

imgReader(item);

}

}

function imgReader(obj) {

let $messageBox=$('#message-boxID');

let file = obj.getAsFile(),

reader = new FileReader();

reader.readAsDataURL(file);

reader.onload = function (e) {

let img = new Image();

img.src = e.target['result'];

img.className = 'chatImg';

$messageBox.append(img);

setTimeout(() => {

$messageBox.scrollTop($messageBox[0].scrollHeight);

}, 0)

};

}

}

本地图片选择

1

<input id="upImg" name="fileTrans" type="file" (change)="onFileSelect($event)"/>

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

* 选择图片

* @param event

*/

files:any[]=[];

onFileSelect(event) {

this.files=[];

let files = event.dataTransfer ? event.dataTransfer.files : event.target.files;

let file;

for (let i = 0; i < files.length; i++) {

file = files[i];

if (this.isImage(file)) {

file.objectURL = this.sanitizer.bypassSecurityTrustUrl((window.URL.createObjectURL(files[i])));

this.files.push(files[i]);

}

}

let fileUrl = file.objectURL.changingThisBreaksApplicationSecurity;

let img = new Image();

img.src = fileUrl;

img.className = 'chatImg';

$('#message-boxID').append(img);

}

图片上传服务器

前端angular上传图片到服务器,必然是ajax请求的方式,将图片数据转成二进制流传给后端了。

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

url:string="http://localhost:8080/upload";

progress:number=0;

uploadPic(formData):Promise<any> {

let xhr = new XMLHttpRequest(),

return new Pormise(resolve,reject){

xhr.upload.addEventListener('progress', (e: ProgressEvent) => {

if(e.lengthComputable) {

this.progress = Math.round((e.loaded * 100) / e.total);

}

}, false);

xhr.onreadystatechange = () => {

if(xhr.readyState == 4) {

this.progress = 0;

if(xhr.status >= 200 && xhr.status < 300)

resolve({xhr: xhr, files: this.files});

else

reject({xhr: xhr, files: this.files});

}

};

xhr.open('POST', this.url, true);

xhr.setRequestHeader("Authorization", "Basic " + localStorage.getItem('jwt'));

xhr.send(formData);

}

}

将以上方法写到一个upload-file.servie.ts中。然后其他地方就可以使用uploadFileService.uploadPic()方法调用了。

这里后端代码忽略,后端Java或者nodejs都很简单,接收文件二进制流保存,或者是上传到百度云与阿里云。

信息发送按钮处理

发送信息处理,需要处理好文本信息和图片信息两种。

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

51

52

53

54

55

56

57

* dataURL to blob, ref to https://gist.github.com/fupslot/5015897

* @param dataURI

* @returns {Blob}

*/

function dataURItoBlob(dataURI) {

var byteString = atob(dataURI.split(',')[1]);

var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

var ab = new ArrayBuffer(byteString.length);

var ia = new Uint8Array(ab);

for (var i = 0; i < byteString.length; i++) {

ia[i] = byteString.charCodeAt(i);

}

return new Blob([ab], {type: mimeString});

}

* 发送消息

* @param taskValue

*/

sendMessage() {

let dateTime = this.dateFromat.FormatDate(new Date());

let value = $('#message-boxID').html();

let isImg = value.includes('<img');

if (isImg) {

let formData = new FormData();

let dataURL="";

let src=$(value)[0].src;

if(src.includes('data:images')){

dataURL=src;

let blob = dataURItoBlob(dataURL);

formData.append('file', blob);

}else if(src.includes('blob:http')){

for(let i = 0; i < this.files.length; i++) {

formData.append('file', this.files[i], this.files[i].name);

}

}

this.uploadFileService.uploadPic(formData).then(result=>{

console.log(result);

}).catch(err=>{

console.log('图片上传失败'+err);

})

}else{

}

}

<完>

推荐文章