node.js字符串解base64转byte
时间: 2024-10-17 18:10:07 浏览: 33
在Node.js中,你可以使用内置的`Buffer`对象和`atob()`函数来将Base64编码的字符串转换为字节(二进制数据)。下面是一个简单的例子:
```javascript
const { Buffer } = require('buffer');
function base64ToByte(base64String) {
// 使用atob()函数解码Base64字符串
const byteStr = Buffer.from(atob(base64String), 'binary');
return byteStr;
}
// 示例用法
const base64Input = 'SGVsbG8gV29ybGQ='; // 假设这是Base64编码的"Hello World"
const bytes = base64ToByte(base64Input);
console.log(bytes.toString('hex')); // 输出原始字节的十六进制表示
```
在这个示例中,`Buffer.from()`方法用于创建一个新的Buffer对象,它接受两个参数:解码后的字符串和指定的编码格式(这里是`'binary'`,因为`atob()`返回的是二进制字符串)。
相关问题
node.js 后台将file文件发到java后台用MultipartFile接收
在Node.js向Java后端发送文件时,由于它们运行在不同的技术栈下,你需要中间件来转换和传递文件。常见的做法是先将Node.js生成的文件流转换成Base64字符串,然后发送给Java,Java后端再从Base64解码恢复原始文件。这里以Express为例:
**Node.js(发送文件至Java)**
首先,安装必要的模块,如`multer`用于处理文件,`axios`用于HTTP请求:
```bash
npm install multer axios
```
然后,在Node.js中处理文件并将Base64编码发送给Java:
```javascript
const express = require('express');
const multer = require('multer');
const axios = require('axios');
const app = express();
const upload = multer({ dest: 'uploads/' });
app.post('/upload-to-java', upload.single('file'), async (req, res) => {
try {
const fileBuffer = await new Promise((resolve) => {
req.file.stream.pipe(buffer()).on('finish', () => resolve(buffer()));
});
const base64Data = Buffer.from(fileBuffer).toString('base64');
const response = await axios.post(
'http://your-java-backend-url/upload-file', // 替换为实际的Java API URL
{ fileBase64: base64Data }, // 将文件内容作为Base64字段
{ headers: { 'Content-Type': 'application/json' } }
);
res.json(response.data);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.listen(3000, () => console.log('Server started on port 3000'));
```
**Java(接收并解码Base64文件)**
在Java方面,你需要一个能接受Base64编码文件的API。这里是一个简单的Spring Boot示例,假设使用了`spring-boot-starter-web`和`jackson-databind`:
```java
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@RestController
public class FileUploadController {
@PostMapping("/upload-file")
public void receiveFile(@RequestParam("fileBase64") String fileBase64, HttpServletResponse response) throws IOException {
byte[] decodedBytes = Base64.getDecoder().decode(fileBase64);
Path filePath = Paths.get("path/to/save/file", "received_file.txt"); // 替换为实际保存路径
Files.write(filePath, decodedBytes);
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println("File received and saved successfully");
}
}
```
try { // 获取当前日期 LocalDate currentDate = LocalDate.now(); // 定义日期格式 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // 转换为指定格式的字符串 String dateString = currentDate.format(formatter); // 构建URL对象 URL url = new URL(API_BASE_URL + "?begin=" + dateString + "&Methodname=" + URLEncoder.encode(str, "UTF-8")); // 创建HttpURLConnection对象 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置请求方法为GET connection.setRequestMethod("GET"); // 设置Basic认证信息 String auth = API_USERNAME + ":" + API_PASSWORD; byte[] authBytes = auth.getBytes(StandardCharsets.UTF_8); String authHeaderValue = "Basic " + Base64.getEncoder().encodeToString(authBytes); connection.setRequestProperty("Authorization", authHeaderValue); // 设置字符编码为UTF-8 connection.setRequestProperty("Accept-Charset", "UTF-8"); // 发送请求 int responseCode = connection.getResponseCode(); // 读取响应数据 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8)); StringBuilder responseBuilder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { responseBuilder.append(line); } String response = responseBuilder.toString(); // 关闭连接 connection.disconnect(); // 返回响应数据 ObjectMapper objectMapper = new ObjectMapper(); JsonNode rootNode = objectMapper.readTree(response); String ls = rootNode.get("data").get(0).toString(); return ls; } catch (Exception e) { e.printStackTrace(); return "Error: " + e.getMessage(); }其中ls的值是"{\"ls\":\"603\"}",修改一下,ls只需要”603“
在获取到 `ls` 的值时,可以使用 `JsonNode` 的 `get()` 方法获取到 `ls` 字段对应的值,然后使用 `String` 的 `replaceAll()` 方法去除多余的字符,具体修改如下:
```
try {
// 获取当前日期
LocalDate currentDate = LocalDate.now();
// 定义日期格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// 转换为指定格式的字符串
String dateString = currentDate.format(formatter);
// 构建URL对象
URL url = new URL(API_BASE_URL + "?begin=" + dateString + "&Methodname=" + URLEncoder.encode(str, "UTF-8"));
// 创建HttpURLConnection对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为GET
connection.setRequestMethod("GET");
// 设置Basic认证信息
String auth = API_USERNAME + ":" + API_PASSWORD;
byte[] authBytes = auth.getBytes(StandardCharsets.UTF_8);
String authHeaderValue = "Basic " + Base64.getEncoder().encodeToString(authBytes);
connection.setRequestProperty("Authorization", authHeaderValue);
// 设置字符编码为UTF-8
connection.setRequestProperty("Accept-Charset", "UTF-8");
// 发送请求
int responseCode = connection.getResponseCode();
// 读取响应数据
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
StringBuilder responseBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
responseBuilder.append(line);
}
String response = responseBuilder.toString();
// 关闭连接
connection.disconnect();
// 返回响应数据
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(response);
String ls = rootNode.get("data").get(0).get("ls").asText().replaceAll("[^\u4e00-\u9fa5^\\d]", "");
return ls;
} catch (Exception e) {
e.printStackTrace();
return "Error: " + e.getMessage();
}
```
在上述代码中,使用了 `JsonNode` 的 `asText()` 方法将 `ls` 的值转化为字符串类型,然后使用 `replaceAll()` 方法去除多余字符,只保留数字和中文。
阅读全文