一键提交两种表格的问题

时间:2019-06-06 15:58:34

标签: node.js ajax

我正在尝试使用一个提交按钮(使用ajax)向node.js服务器中的两条不同的路线提交两种形式。第一种形式用于图片,第二种形式用于图片的细节。当第一个表单显示其路由请求时,将显示“ HTTP 500(内部服务器错误)”,而第二个表单则显示“ net :: ERR_EMPTY_RESPONSE”。图片将上传到cloudinary,所以我已经使用它们的API进行了一些配置,我还使用了EJS模板。图片已成功上载到没有ajax的cloudinary,但是我需要ajax才能立即上传图片及其详细信息。我不知道我到底在做什么错,任何帮助将不胜感激。

'ejs'

<form enctype = 'multipart/form-data' id = 'formone'>
    <input type = 'file' id = 'photo' name = 'image'/>
</form>

<form id = 'formtwo'> 
    <p>Department: <input type = "text" id = "department" name = "department" placeholder = "Department"/></p>
     <p>Course Code: <input type = "text" id = "course_code" name = "course_code" placeholder = "Course Code"/></p>
     <p>Course Name: <input type = "text" id = "course_name" name = "course_name" placeholder = "Course Name"/></p>
     <p>Year: <input type = "number" id = "year" name = "year" placeholder = "Year"/></p> 
</form>

<input type = "submit" name = "submit" id = "submit"/>
'ajax'

function submitAction() {
    var form1 = $( '#formone' ).serialize();
    var form2 = $( "#formtwo" ).serialize()

    $.ajax( {
        url: '/api/images',
        type: 'POST',
        dataType: "image/jpg",
        data: form1
    } );

    $.ajax( {
        url: '/imagedetails',
        type: 'POST',
        dataType: "json", 
        data: form2
    } );
}
'cloudinary config'

cloudinary.config( {
    cloud_name: config.cloudName,
    api_key: config.apiKey,
    api_secret: config.apiSecret
} );

const storage = cloudinaryStorage( {
    cloudinary: cloudinary,
    folder: "pqrepo",
    allowedFormats: ["jpg", "png"],
    transformation: [{ width: 2000, height: 2000, crop: "limit" }]
} );

const parser = multer( { storage: storage } );
'/api/images route'

app.post( '/api/images', parser.single( "image" ), ( req, res ) => {
    console.log( req.file );

    var events = JSON.parse( JSON.stringify( req.file ) );

    var newUpload = new Upload();

    newUpload.url = events.secure_url;
    newUpload.id = events.public_id;
    newUpload.upload_date = events.created_at;

    newUpload.save( function( err, savedObject ) {
        if( err ) {
            res.json( err );
        } else {
            res.redirect( '/uploadsuccess' );
        }
    } );
} );

2 个答案:

答案 0 :(得分:0)

尝试如下:

//ajax call
var dataObj = new FormData(); // Creating object of FormData class
var file_data = jQuery("input[name='image']").prop("files")[0]; // Getting the properties of file from file field
dataObj.append("photo", file_data);
dataObj.append("department", jQuery("#department").val());
dataObj.append("course_code", jQuery("#course_code").val());
dataObj.append("course_name", jQuery("#course_name").val());
dataObj.append("year", jQuery("#year").val());
console.log("dataObj", dataObj);

 jQuery.ajax({
    type: "POST",
    url: "./api",
    data: dataObj,
    //contentType: "application/x-www-form-urlencoded; charset=utf-8",
    enctype: 'multipart/form-data',
    dataType: "json",
    // Tell jQuery not to process data or worry about content-type
    // You *must* include these options!
    cache: false, // To unable request pages to be cached
    contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
    processData: false, // To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
    success: function (res) {
       //success
       console.log("success", res);
    },
    error: function (xhr, errorType, exception) {
        //error
        console.log("xhr", xhr);
        console.log("errorType", errorType);
        console.log("exception", exception);

    },
    failure: function (failure) {
        //failure
        console.log("failure", failure);

    }
});
//end ajax

将网址更改为您的网址

答案 1 :(得分:0)

@slon 修改后的代码:

var picObj = new FormData();
    var dataObj = new FormData();

    var file_data = jQuery( "input[name='image']" ).prop( "files" )[0];

    picObj.append( "photo", file_data );
    dataObj.append( "department", jQuery( "#department" ).val() );
    dataObj.append( "course_code", jQuery( "#course_code" ).val() );
    dataObj.append( "course_name", jQuery( "#course_name" ).val() );
    dataObj.append( "year", jQuery( "#year" ).val() );
    console.log( "dataObj", dataObj );
    console.log( "picObj", picObj );

    jQuery.ajax( { 
        type: "POST",
        url: "/api/images",
        data: picObj,
        enctype: "multipart/form-data",
        dataType: "json",
        cache: false,
        contentType: false,
        processData: false,
        success: function( res ) {
            console.log( "success", res );
        }, 
        error: function (xhr, errorType, exception) {
            console.log("xhr", xhr);
            console.log("errorType", errorType);
            console.log("exception", exception);
        },
        failure: function (failure) {
            console.log("failure", failure);
        }
    } );

    jQuery.ajax( { 
        type: "POST",
        url: "/imagedetails",
        data: dataObj,
        dataType: "json",
        cache: false,
        contentType: false,
        processData: false,
        success: function( res ) {
            console.log( "success", res );
        }, 
        error: function (xhr, errorType, exception) {
            console.log("xhr", xhr);
            console.log("errorType", errorType);
            console.log("exception", exception);
        },
        failure: function (failure) {
            console.log("failure", failure);
        }
    } );