【问题标题】:Upload images/videos to server using Servlet and Android Studio使用 Servlet 和 Android Studio 将图像/视频上传到服务器
【发布时间】:2018-08-01 18:07:55
【问题描述】:

我正在尝试将通过设备相机拍摄的图像/视频上传到特定文件夹中的服务器,稍后可以在仪表板中检索该文件夹。

我浏览了很多帖子和教程,它们基本上都是使用 JSP 选择文件然后上传,或者他们使用 PHP 作为服务器端代码来上传。

我的整个后端都是用 JAVA SERVLET 开发的,我需要包含这个上传/下载功能。

基本上我想要的是使用 Retrofit 或 Volley 发出一个 POST 请求来发出服务器请求,并且应该上传文件。 (就像我们使用 POSTMAN 触发 api 调用并选择图像作为二进制文件上传)。

我尝试过的链接:

Link 1Link 2Link 3 等等。它们都包括JSP或选择文件的东西,我需要将媒体(图像/视频)作为参数传递给POST请求。

【问题讨论】:

    标签: android servlets


    【解决方案1】:

    所以我终于设法实现了。我必须发布图片/视频以及与该媒体对应的 JSON。

    我的解决方法如下:

    @WebServlet("/ImageUploadServlet")
    @MultipartConfig
    public class ImageUploadServlet extends HttpServlet {
    ..............
    .............
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        long req_received_time=System.currentTimeMillis();
        String to_be_saved_location="";
        System.out.println("JSON received is : "+request.getParameter("input_json"));    
        JSONObject req = null;
        try {
            req = readPOST(request.getParameter("input_json"));
            to_be_saved_location = "your_location";
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            SqlUtil.incident_reporting(xxx);// function to enter data in sql
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        InputStream in = request.getPart("image").getInputStream();//change it to video(it's just a parameter name)
        OutputStream out = new FileOutputStream("/Users/driftking9987/Documents/Stuffs/"+to_be_saved_location+".jpg");//Add .mp4 for video
        //OutputStream out = new FileOutputStream("/var/www/html/media/abc.mp4");
        copy(in, out); //The function is below
        out.flush();
        out.close();
    
    }
    
    public static long copy(InputStream input, OutputStream output) throws IOException {
        byte[] buffer = new byte[4096];
    
        long count = 0L;
        int n = 0;
    
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
            count += n;
        }
        return count;
    }
    

    在服务器上保存时,我给了tomcat用户写入media文件夹的权限。

    下面是邮递员的截图。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-28
      • 2011-07-09
      • 2023-04-09
      • 2011-06-16
      • 2016-06-10
      • 1970-01-01
      相关资源
      最近更新 更多