我只需要将我的Android设备上的视频上传到我的Java后端,在阅读了一些StackOverflow线程后,我了解到我需要将我的视频作为Multipart请求发布到Java后端。
我设法实现了以下功能,它基本上将视频文件作为多部分POST请求进行POST。
Android客户端:
private void uploadVideo(String videoPath) throws ParseException, IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("MY_SERVER_URL");
FileBody filebodyVideo = new FileBody(new File(videoPath));
StringBody title = new StringBody("Filename: " + videoPath);
StringBody description = new StringBody("This is a description of the video");
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("video", filebodyVideo);
reqEntity.addPart("title", title);
reqEntity.addPart("description", description);
httppost.setEntity(reqEntity);
// DEBUG
HttpResponse response = httpclient.execute( httppost );
HttpEntity resEntity = response.getEntity( );
// DEBUG
System.out.println( response.getStatusLine( ) );
if (resEntity != null) {
System.out.println( EntityUtils.toString(resEntity) );
} // end if
if (resEntity != null) {
resEntity.consumeContent( );
} // end if
httpclient.getConnectionManager( ).shutdown();
}
我的问题是,如何从Java后端接收文件?这是我需要修改的后端方法。有人可以指出我如何从后端接收视频文件吗?
我现在拥有的东西:
@Path("/user")
public class UserAPI {
@POST
//To receive the file, What do I add below instead of the lines I've commented.
//@Produces(MediaType.APPLICATION_JSON)
//@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Path("/postvideo")
public VideoResponse PostVideo(){
//My code
}
}
答案 0 :(得分:1)
我是这样做的(没有错误处理,验证和东西)。
@POST
@Path("/")
@Consumes("multipart/form-data")
public Response uploadFileMultipart(MultipartFormDataInput input) {
Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
List<InputPart> inputParts = uploadForm.get("video");
String videoFileName = "GENERATE_YOUR_FILENAME_HERE.mp4";
File file = new File(filename);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fop = new FileOutputStream(file);
for (InputPart inputPart : inputParts) {
InputStream inputStream = inputPart.getBody(InputStream.class, null);
byte[] content = IOUtils.toByteArray(inputStream);
fop.write(content);
}
fop.flush();
fop.close();
return Response.status(HttpStatus.SC_OK).build();
}