无法将多张图片传递到服务器Nodejs

时间:2020-01-21 08:17:27

标签: javascript android node.js retrofit2 multer

我使用Android Studio创建了一个应用程序,并使用NodeJs在服务器端创建了一个应用程序。我试图传递单个图像并能够传递。这次,我想将多个图像传递到服务器,但是当我开始在Api.kt文件中将参数从image:MultipleBody.Part更改为images:List<MultipartBody.Part>时,在服务器端收到了一条错误消息。我不知道我做错了什么。希望可以帮助我解决这个问题。预先谢谢你。

$节点应用程序正在侦听端口4545 ... MulterError:意外字段 在wrappedFileFilter(C:\ Users \ user \ Documents \ GitHub \ EIS-API \ node_modules \ multer \ index.js:40:19) 在Busboy。 (C:\ Users \ user \ Documents \ GitHub \ EIS-API \ node_modules \ multer \ lib \ make-middleware.js:114:7) 在Busboy.emit(events.js:223:5) 在Busboy.emit(C:\ Users \ user \ Documents \ GitHub \ EIS-API \ node_modules \ busboy \ lib \ main.js:38:33) 在PartStream。 (C:\ Users \ user \ Documents \ GitHub \ EIS-API \ node_modules \ busboy \ lib \ types \ multipart.js:213:13) 在PartStream.emit(events.js:223:5) 在HeaderParser。 (C:\ Users \ user \ Documents \ GitHub \ EIS-API \ node_modules \ dicer \ lib \ Dicer.js:51:16) 在HeaderParser.emit(events.js:223:5) 在HeaderParser._finish(C:\ Users \ user \ Documents \ GitHub \ EIS-API \ node_modules \ dicer \ lib \ HeaderParser.js:68:8) 在SBMH。 (C:\ Users \ user \ Documents \ GitHub \ EIS-API \ node_modules \ dicer \ lib \ HeaderParser.js:40:12) MulterError:意外字段 在wrappedFileFilter(C:\ Users \ user \ Documents \ GitHub \ EIS-API \ node_modules \ multer \ index.js:40:19) 在Busboy。 (C:\ Users \ user \ Documents \ GitHub \ EIS-API \ node_modules \ multer \ lib \ make-middleware.js:114:7) 在Busboy.emit(events.js:223:5) 在Busboy.emit(C:\ Users \ user \ Documents \ GitHub \ EIS-API \ node_modules \ busboy \ lib \ main.js:38:33) 在PartStream。 (C:\ Users \ user \ Documents \ GitHub \ EIS-API \ node_modules \ busboy \ lib \ types \ multipart.js:213:13) 在PartStream.emit(events.js:223:5) 在HeaderParser。 (C:\ Users \ user \ Documents \ GitHub \ EIS-API \ node_modules \ dicer \ lib \ Dicer.js:51:16) 在HeaderParser.emit(events.js:223:5) 在HeaderParser._finish(C:\ Users \ user \ Documents \ GitHub \ EIS-API \ node_modules \ dicer \ lib \ HeaderParser.js:68:8) 在SBMH。 (C:\ Users \ user \ Documents \ GitHub \ EIS-API \ node_modules \ dicer \ lib \ HeaderParser.js:40:12)

Api.kt

  @Multipart
    @POST("perkhidmatan_rumput/api/PostPemantauanPerkhidmatanPotingRumput" +
            "/{zon}/{syarikat}/{alamat_syarikat}/{nama_penyelia}/{taman}/{bulan}/{tahun}" +
            "/{masa}/{timeAMPM}/{pusingan}/{status}/{catatan}/{state}/{entryOperator}")
    fun  postPemantauanPerkhidmatanPotingRumput(
        @Path("zon")zon:String,
        @Path("syarikat")syarikat:String,
        @Path("alamat_syarikat")alamat_syarikat:String,
        @Path("nama_penyelia")nama_penyelia:String,
        @Path("taman")taman:Int,
        @Path("bulan")bulan:String,
        @Path("tahun")tahun:String,
        @Path("masa")masa:String,
        @Path("timeAMPM")timeAMPM:String,
        @Path("pusingan")pusingan:String,
        @Path("status")status:String,
        @Path("catatan")catatan:String,
        @Path("state")state:String,
        @Path("entryOperator")entryOperator:String,
        @Part images:List<MultipartBody.Part>
        //@Part image:MultipartBody.Part?

    ):LiveData<GenericApiResponse<OnResponse>>

PemoViewModel.kt

public fun  getAllImages():List<MultipartBody.Part>?{
    var info = getCurrentViewStateOrNew()
    var pic:List<GambarSebelum>? = info.gambarSebelum
    var images = mutableListOf<MultipartBody.Part>()
    pic?.let {

       for ( item in it){

           var multipartBody: MultipartBody.Part? = null

           item.url?.path?.let { filePath ->
               val imageFile = File(filePath)

               val requestBody =
                   RequestBody.create(
                       MediaType.parse("image/*"),
                       imageFile
                   )

               multipartBody = MultipartBody.Part.createFormData(
                   "image",
                   imageFile.name,
                   requestBody
               )
           }

           images.add(multipartBody!!);
       }


    }

    return images;

}

PemoFragment.kt

  _binding.btnLogin.setOnClickListener {
            if(!isFill()){
                Toast.makeText(requireContext(),"sila penuhkan ruang diatas..",Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            var bulan:String = CALENDER.valueOf(_binding.idBulanSpinner.selectedItem.toString()).value
            var taman:Int? = _viewModel.getTamanIdByTamanName(_binding.idTamanSpinner.selectedItem.toString())
            var pusingan:String? = _viewModel.getPusinganByPusinganName(_binding.idPusinganSpinner.selectedItem.toString())
            var status:String? = _viewModel.getStatusByStatusName(_binding.idStatusSpinner.selectedItem.toString())
            var images:List<MultipartBody.Part>? = _viewModel.getAllImages()

            if(taman != null && pusingan != null && status != null){



                //insert information to server (database)
                _viewModel.setStateEvent(
                    FormRumputStateEvent.SubmitPemantauanForm(
                        PemantauanPotongRumputResponse(
                            _binding.idZonsSpinner.selectedItem.toString(),
                            _binding.idNamaSyarikatEdit.text.toString(),
                            _binding.idAlamatSyarikat.text.toString(),
                            _binding.idNamaPenyeliaKontraktorEdit.text.toString(),
                            taman,
                            bulan,
                            _binding.idTahunEdit.text.toString(),
                            _binding.idMasaEdit.text.toString(),
                            _binding.idAmPmSpinner.selectedItem.toString(),
                            pusingan,
                            status,
                            _binding.idCatatanEdit.text.toString(),
                            STATE_STATUS.CREATE.name,
                            "ADMIN",
                            images!!
                        )
                    ))
            }else{
                Toast.makeText(requireContext(),"[Error] Taman,Bulan,pusingan or status has Problem..",Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

        }

PemantauanPotongRumputResponse

data class PemantauanPotongRumputResponse(
    @Expose
    @SerializedName("zon")
    val zon:String,
    @Expose
    @SerializedName("syarikat")
    val syarikat:String,
    @Expose
    @SerializedName("alamat_syarikat")
    val alamat_syarikat:String,
    @Expose
    @SerializedName("nama_penyelia")
    val nama_penyelia:String,
    @Expose
    @SerializedName("taman")
    val taman:Int,
    @Expose
    @SerializedName("bulan")
    val bulan:String,
    @Expose
    @SerializedName("tahun")
    val tahun:String,
    @Expose
    @SerializedName("masa")
    val masa:String,
    @Expose
    @SerializedName("timeAMPM")
    val timeAMPM:String,
    @Expose
    @SerializedName("pusingan")
    val pusingan:String,
    @Expose
    @SerializedName("status")
    val status:String,
    @Expose
    @SerializedName("catatan")
    val catatan:String,
    @Expose
    @SerializedName("state")
    val state:String,
    @Expose
    @SerializedName("entryOperator")
    val entryOperator:String,
    @Expose
    @SerializedName("images")
    val images:List<MultipartBody.Part>

)

服务器端 NODE.JS

router.post('/api/PostPemantauanPerkhidmatanPotingRumput/:zon/:syarikat/:alamat_syarikat/'+
          ':nama_penyelia/:taman/:bulan/:tahun/:masa/:timeAMPM/:pusingan/:status/:catatan/:state/'+
          ':entryOperator', upload.array('images',9),(req,res,next) =>{

               try{
                    const file = req.files;
                    if (!file) {
                        res.status(400).json({
                            "status": "failed",
                            "code" : "400",
                            "message" : "Please upload file"
                        });
                    }

                    res.status(200).json({
                        "status": "success",
                        "code" : "200",
                        "message" : "file uploaded successfully"
                    });
                    console.log(file);
                    console.log(req.body);
                }catch(err){
                    console.log(error.message);
                    res.status(200).json({
                        "status": "failed",
                        "code" : "500",
                        "message" : error.message
                    });
                }


})

1 个答案:

答案 0 :(得分:0)

能够解决问题。只要确保MultipartBody.Part.createFormData处的第一个参数“ images”与服务器端参数upload.array("images")

相同
multipartBody = MultipartBody.Part.createFormData(
                   "images",
                   imageFile.name,
                   requestBody
               )

PemoViewMode.kt

public fun  getAllImages():List<MultipartBody.Part>?{
    var info = getCurrentViewStateOrNew()
    var pic:List<GambarSebelum>? = info.gambarSebelum
    var images = mutableListOf<MultipartBody.Part>()
    pic?.let {
       for ( item in it){
           var multipartBody: MultipartBody.Part? = null
           item.url?.path?.let { filePath ->
               val imageFile = File(filePath)
               val requestBody =
                   RequestBody.create(
                       MediaType.parse("image/*"),
                       imageFile
                   )
               multipartBody = MultipartBody.Part.createFormData(
                   "images",
                   imageFile.name,
                   requestBody
               )
           }
           images.add(multipartBody!!);
       }
    }
    return images;
}

服务器端(NODEJS)

router.post('/api/PostPemantauanPerkhidmatanPotingRumput/:zon/:syarikat/:alamat_syarikat/'+
          ':nama_penyelia/:taman/:bulan/:tahun/:masa/:timeAMPM/:pusingan/:status/:catatan/:state/'+
          ':entryOperator', upload.array('images',9),(req,res,next) =>{

               try{
                    const file = req.files;
                    if (!file) {
                        res.status(400).json({
                            "status": "failed",
                            "code" : "400",
                            "message" : "Please upload file"
                        });
                    }

                    res.status(200).json({
                        "status": "success",
                        "code" : "200",
                        "message" : "file uploaded successfully"
                    });
                    console.log(file);
                    console.log(req.body);
                }catch(err){
                    console.log(error.message);
                    res.status(200).json({
                        "status": "failed",
                        "code" : "500",
                        "message" : error.message
                    });
                }


})