缘起
直接搜标题很难搜到解决方案,找了好久…后来看到一个app.use(bodyparser.json({type:mutlipart/formdata}))
想到bodyparser是否也有其他选项可以切换到text?直接去搜bodyparser用法…得到答案:
源码很简单
js服务端
app.use(bodyParse.text({limit:"10Mb"})) //limit控制文件大小
app.post("/file", (req, res) => {
console.log("已收到"+__dirname)
var UUID=req.get("UUID")
var nowID = findPhoneUser(UUID)
//如果对你有用就点个赞把!!!!!
var path = __dirname+"/file/"+req.get("UUID")
console.log("已收到"+path)
if(fs.existsSync(path)){
fs.writeFile(path+fileName,req.body,(err)=>{log(err)})
console.log("文件已保存"+path)
}
else{
fs.mkdir(path,(err)=>{log(err)})
fs.writeFile(path+fileName,req.body,(err)=>{log(err)})
console.log("文件已保存"+path)
}
Android发送端
public void upload(String url, String filePath, String UUID,String fileName) throws Exception {
File file2 = new File(filePath);
Log.e("statu",filePath);
//使用MultipartBody上传多个文件,Builder构建着
new Thread(()->{
Log.e("真","新");
//创建 MediaType 设置上传文件类型
MediaType MEDIATYPE = MediaType.parse("text/plain; charset=utf-8");
//获取请求体
RequestBody requestBody = RequestBody.create(MEDIATYPE, file2);
//创建请求
Request request = new Request.Builder().url(url).addHeader("UUID",UUID).addHeader("fn",fileName)
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
Log.e("请求失败,异常信息为: {}", e.getMessage());
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response)
throws IOException {
Log.e("请求成功,返回信息为: {}", response.body().toString());
}
});
}).start();
}
控制台打印
收到/www
//文件内容====================================
GYRO;0.007;85331.676;-0.00845;-0.00897;0.00042;3;1698884942483
ACCE;0.007;85331.688;-0.08543;1.48648;9.83542;3;1698884942484
MAGN;0.008;85331.688;-8.56250;-3.43750;-23.25000;3;1698884942484
AHRS;0.008;85331.692;8.764804;0.618179;-88.365837;0.05854500;-0.04939800;-0.69460797;3;1698884942484
LACC;0.008;85331.692;0.00650;-0.00370;-0.05160;0;1698884942485
GYRO;0.009;85331.696;0.00347;0.00354;-0.00080;3;1698884942485
//====================================
已收到/www/file/63968661bc244474a5bcd8cd8c6d47b6