使用Multipart的文件上传在nodejs中失败

时间:2016-06-02 04:42:26

标签: javascript node.js multer

我正在尝试使用multipart上传节点js中的文件,我得到了无法POST错误?我对节点js完全不熟悉。所以你能帮我解决我做错的事吗? 我的代码? HTML

var express  = require('express');
var app      = express();
var multer  =   require('multer');
app.use(express.static(__dirname));
app.get('/', function(request, response){
    response.sendFile("./index.html"); 
});

var storage =   multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './uploads');
  },
  filename: function (req, file, callback) {
    callback(null, file.fieldname + '-' + Date.now());
  }
});
var upload = multer({ storage : storage}).single('fileUpload');


app.post('/api/uploadfile',function(req,res){
    upload(req,res,function(err) {
        if(err) {
            return res.end("Error uploading file.");
        }
        res.end("File is uploaded");
    });
});


app.listen(8080);
console.log("App listening on port 8080");

Server.js

package com.example.shriram.lordmuruga;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;

import com.firebase.client.Firebase;

public class MainActivity extends AppCompatActivity {

    String muruga2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Firebase.setAndroidContext(this);

    }


    public void additem() {

        EditText muruga = (EditText) findViewById(R.id.muruga);
        muruga2 = muruga.getText().toString();
        Firebase ref = new Firebase("https://project-7493703210.firebaseio.com/");
        ref.child("Name").setValue(muruga2);
        Intent inti = new Intent(MainActivity.this,NextActivity.class);
        startActivity(inti);
    }
}

错误信息如下:

  

上传文件时出错

1 个答案:

答案 0 :(得分:9)

我试过你的代码,它在这里工作。原因可能是,

1)你错过了表格标签的关闭

<html>
<form id       =  "uploadForm"
     enctype   =  "multipart/form-data"
     action    =  "/api/uploadfile"
     method    =  "post"
>
<input type="file" name="fileupload"  /> 
<input type="submit" value="Upload file" name="submit">
</form>
</html>

2)确保您有一个名为 - &gt;的文件夹。上传