首页 > 解决方案 > 使用 node.js 上传 HTTP 文件正在更改文件

问题描述

我在将带有 node.js 的 jpg 文件上传到我的 tomcat 服务器时遇到问题 - 在上传的某处文件内容已更改。我认为,它与编码有关,但我不知道我错过了什么。

node.js 代码是:

var agentOptions;
var agent;

agentOptions = {
  host: 'this.is.my.server'
, port: '8443'
, path: '/'
, rejectUnauthorized: false
};

agent = new https.Agent(agentOptions);

var binaryFilename = "image.jpg";
var fContent = fs.readFileSync( binaryFilename );    
console.log( "file size =  " + fContent.length );

var boundary = '69b2c2b9c464731d'
var content = "--"+boundary+"\r\n"
        + "Content-Disposition: form-data; name=\"file\"; filename=\"image.jpg\"\r\n"
        + "Content-Type: application/octet-stream\r\n"
        + "Content-Transfer-Encoding: BINARY\r\n"
        + "\r\n"
        + fContent + "\r\n"
        + "--"+boundary+"--\r\n"

postOptions = {
    headers: {
      'Content-Type': 'multipart/form-data; boundary='+boundary ,
      'Content-Length': Buffer.byteLength(content) ,
      'Authorization': 'Basic ABCEDFE..' 
    } ,

    host: 'this.is.my.server' ,
    port: '8443' ,
    path: '/restservices/uploadimage?data=value&data2=value2' ,
    method: 'POST' ,
    strictSSL: false ,
    agent: agent
} ; 

// Set up the request
post_req = https.request(
    postOptions, 
    function(res) {
        // 
      res.setEncoding('utf8') ;

      res.on('data', function (chunk) {
          console.log('Response: ' + chunk) ;
      }) ;

    }) ;

// post the data
post_req.write(content) ;
post_req.end() ;

服务器上的 Java 代码以

@RequestMapping(value = "/uploadimage", method = RequestMethod.POST )
public @ResponseBody String uploadpreview(@RequestParam String data, @RequestParam String data1, @RequestParam("file") MultipartFile file) {
    if (!file.isEmpty()) {
        ....

上传前图片的开头: 上传前的图片

上传后图片开始: 上传前的图片

最高位设置的每个字节都转换为三个字节 EF BF BD

我尝试了几件事,也许我错过了一些简单的东西 - 目前我不知道我做错了什么。

感谢您的任何想法和提示

克劳斯

标签: node.jshttppostupload

解决方案


这是另一个尝试:

const https = require('https');
const formData = require('form-data')();

var binaryFilename = process.argv[2] || 'image.jpg';

let request = https.request({
    host: 'this.is.my.server'
    port: '8443',
    path: '/',
    method: 'POST',
    headers: formData.getHeaders()
}, (res) => {
    res.on('data', (data) => {
       console.log('Data received: ', data.toString()); 
    });
});

request.on("error", (e) => {
    console.error(e);
});

formData.append('image_file', require("fs").createReadStream(binaryFilename));
formData.pipe(request);

推荐阅读