URL编码、解码

URL编码:
 通过页面传输数据给服务器时,如果包含了一些特殊字符是无法发送的。这时就需要先把要发送的数据转换成URL编码格式,再发送给服务器。服务器会自动识别出数据是使用URL编码过的,然后会自动把数据转换回来

URL编码、解码的4个方法
 encodeURL() encodeURLComponent() decodeURL() decodeURLComponent()
一、区别:
 编码的字符范围不同 encodeURI() > encodeURLComponent()
 
encodeURI() 不包括以下字符:
这里写图片描述 
encodeURIComponent()
 不包括:字母、数字、~!*()’

二、适合场景
 1、如果需要编码整个URL,再使用这个URL,那么用encodeURI()
 eg:

encodeURI("http://www.cnblogs.com/season-huang/some other thing");

 编码后会变为,其中,空格被编码成了%20。

"http://www.cnblogs.com/season-huang/some%20other%20thing";

 如果使用encodeURIComponent(),连 “/” 都被编码了,整个URL已经没法用了。

"http%3A%2F%2Fwww.cnblogs.com%2Fseason-huang%2Fsome%20other%20thing"

 2、当需要编码URL中参数的时候,使用encodeURIComponent()

var param = "http://www.cnblogs.com/season-huang/"; //param为参数
param = encodeURIComponent(param);
var url = "http://www.cnblogs.com?next=" + param;
console.log(url) //"http://www.cnblogs.com?next=http%3A%2F%2Fwww.cnblogs.com%2Fseason-huang%2F"

参数中的 “/” 可以编码,如果用encodeURI()肯定要出问题,因为后面的/是需要编码的

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 3 中,你可以使用 `FileReader` API 和一些辅助函数来将 Base64 编码的图片数据转换为 URL,以便显示在页面上。这是一个简单的示例: 首先,你需要安装一个依赖,如果你的项目中还没有安装 `vue-file-loader`,可以通过 npm 或 yarn 来安装: ```bash npm install vue-file-loader @vue/cli-plugin-vuex --save-dev # 或者 yarn add vue-file-loader @vue/cli-plugin-vuex --dev ``` 然后,在你的项目配置文件(如 `vue.config.js`)中配置 base64 图片处理: ```javascript // vue.config.js module.exports = { configureWebpack: { module: { rules: [ { test: /\.(png|jpe?g|gif)$/i, use: ['file-loader'], options: { esModule: false, name: 'static/images/[name].[hash:8].[ext]', }, }, ], }, }, }; ``` 接着,在你的 Vue 组件中,可以这样实现 Base64 到 URL 的转换: ```html <!-- template.vue --> <template> <div> <img :src="decodeBase64Image(encodedImage)" alt="Decoded Image" /> </div> </template> <script setup> import { ref } from 'vue'; import { createReadStream } from 'fs/promises'; async function decodeBase64Image(base64Image) { const buffer = Buffer.from(atob(base64Image.replace(/^data:image\/\w+;base64,/, '')), 'binary'); const stream = createReadStream({ buffer }); return new Response(stream).blob().then(blob => URL.createObjectURL(blob)); } export default { data() { return { encodedImage: 'data:image/jpeg;base64,base64-encoded-data-goes-here', // 替换为实际的 Base64 数据 }; }, mounted() { this.$watch( () => this.encodedImage, async (newImage) => { if (newImage) { try { this.imageUrl = await decodeBase64Image(newImage); } catch (error) { console.error('Error decoding base64 image:', error); } } }, { deep: true, } ); }, }; </script> ``` 在这个例子中,`decodeBase64Image` 函数会接收 Base64 字符串,将其转换为二进制数据,然后创建一个 ReadableStream,并返回一个包含 URL 的响应。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值