简体   繁体   中英

Upload audio, video and image using FileBody

I want to upload audio, video and image together. I am using the following code:

if (file_name_for_rear_image != null && f_intruder_rear.exists()) {
    ContentType contentType = ContentType.create("image/jpeg");
    FileBody cbFile = new FileBody(f_intruder_rear,contentType);
    multipartEntity.addPart("image[]", cbFile);
}
File video_file = new File(VIDEO_PATH_NAME);
if (VIDEO_PATH_NAME != null && video_file.exists()) {
    ContentType contentType = ContentType.create("video/mp4");
    FileBody cbFile = new FileBody(video_file,contentType);
    multipartEntity.addPart("video", cbFile);
}
File audio_file = new File(audio_file_name);
if (audio_file_name != null && audio_file.exists()) {
    ContentType contentType = ContentType.create("audio/mp3");
    FileBody cbFile = new FileBody(audio_file, contentType);
    multipartEntity.addPart("audio", cbFile);
}

For Image - When I reomve content-type from image filebody, it's getting uploaded. But when I add content-type, it's not working.

For audio/video - No matter if I keep content-type or not, it's not getting uploaded.

I solved it by passing filename in FileBody object.

if (file_name_for_rear_image != null && f_intruder_rear.exists()) {

        ContentType contentType = ContentType.create("image/jpeg");
        FileBody cbFile = new FileBody(f_intruder_rear, contentType,
                "image.jpg");
        multipartEntity.addPart("image[]", cbFile);
    }
    File video_file = new File(VIDEO_PATH_NAME);
    if (VIDEO_PATH_NAME != null && video_file.exists()) {
        ContentType contentType = ContentType.create("video/mp4");
        FileBody cbFile = new FileBody(video_file, contentType, "video.mp4");
        multipartEntity.addPart("video", cbFile);
    }
    File audio_file = new File(audio_file_name);
    if (audio_file_name != null && audio_file.exists()) {
        ContentType contentType = ContentType.create("audio/mp3");
        FileBody cbFile = new FileBody(audio_file, contentType, "audio.mp3");
        multipartEntity.addPart("audio", cbFile);
    }

You can give any file name. Hope it helps someone else because i struggled too much to found this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM