作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我只需将视频从我的 Android 设备上传到我的 Java 后端,在阅读了一些 StackOverflow 线程后,我了解到我需要将我的视频作为多部分请求发布到 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
}
}
最佳答案
这是我的做法(没有错误处理、验证等)。
@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();
}
关于java - Android:将视频作为 POST 请求上传到 Java 后端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36458541/
我是一名优秀的程序员,十分优秀!