【问题标题】:HTTP file upload with node.js is changing the file使用 node.js 上传 HTTP 文件正在更改文件
【发布时间】:2018-05-23 08:48:34
【问题描述】:

我在将带有 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()) {
        ....

上传前图片的开头:

上传后图片的开始:
(来源:dataplan.de

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

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

感谢您的任何想法和提示

克劳斯

【问题讨论】:

  • 我想我找到了一个解决方案(或绕过) - 我可以上传我的文件的 base64 编码版本并在服务器上对其进行解码。这将解决我的问题 - 但我仍然不知道为什么它不起作用..

标签: node.js http post upload


【解决方案1】:

这是另一个尝试:

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);

【讨论】:

  • 我的 node.js 位于 Adob​​e InDesign CEP 扩展中,它是基于 io.js 的旧版本。我尝试使用请求模块,但这是一个“适用于某些客户端/不适用于其他客户端”的问题。所以我尝试只使用基本的 http/https ..
  • 我明白了!这是有道理的,那样你就会受到更多的限制。
猜你喜欢
  • 1970-01-01
  • 2014-02-10
  • 1970-01-01
  • 1970-01-01
  • 2018-12-21
  • 2013-07-10
  • 2016-03-23
  • 2013-02-14
  • 2017-07-26
相关资源
最近更新 更多