如何上传.mp3文件和图像到http服务器?

发布于 2024-11-03 02:17:03 字数 4308 浏览 1 评论 0原文

我将图像上传到服务器的代码是:

String userIdParameter = String.valueOf(userId);
    String fileName = "temporary_holder.jpg";
    HttpURLConnection conn = null;
    DataOutputStream dos = null;

    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;

    String sourceFileUri = HomeScreen.get_path();
    String upLoadServerUri = "http://10.120.10.87:8080/WebImage/UploadImage";

    File sourceFile = new File(sourceFileUri);
    if (!sourceFile.isFile()) {
        Log.e("Huzza", "Source File Does not exist");
        return;
    }
    int serverResponseCode = 0;
    try {

        // open a URL connection to the Servlet
        FileInputStream fileInputStream = new FileInputStream(sourceFile);

        // ------------------ CLIENT REQUEST
        URL url = new URL(upLoadServerUri);

        // Open a HTTP connection to the URL
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true); // Allow Inputs
        conn.setDoOutput(true); // Allow Outputs
        conn.setUseCaches(false); // Don't use a Cached Copy

        // Use a post method.
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");

        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type",
            "multipart/form-data;boundary=" + boundary);
        conn.setRequestProperty("file_name", fileName);
        conn.setRequestProperty("file_name_audio", fileName);
        conn.setRequestProperty("X-myapp-param1", userIdParameter);

        // conn.setFixedLengthStreamingMode(1024);
        // conn.setChunkedStreamingMode(1);

        dos = new DataOutputStream(conn.getOutputStream());

        dos.writeBytes(twoHyphens + boundary + lineEnd);

        dos.writeBytes("Content-Disposition: form-data; name=\"file_name\";filename=\""
            + fileName + "\"" + lineEnd);

        dos.writeBytes(lineEnd);
        
        
            // create a buffer of maximum size
        bytesAvailable = fileInputStream.available();

        int streamSize = (int) sourceFile.length();
        bufferSize = streamSize / 10;

        System.out.println("streamSize" + streamSize);

        buffer = new byte[streamSize];

        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        int count = 0;
        while (bytesRead > 0) {
        progress = (int) (count);
        displayNotification();
        Thread.sleep(500);
        
        dos.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        // bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        count += 10;

        }

        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        // Responses from the server (code and message)
        serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();

        System.out.println("Upload file to serverHTTP Response is : "
            + serverResponseMessage + ": " + serverResponseCode);
        // close streams
        System.out.println("Upload file to server" + fileName
            + " File is written");
        fileInputStream.close();
        dos.flush();
        dos.close();
    } catch (MalformedURLException ex) {
        ex.printStackTrace();
        Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
    } catch (Exception e) {
        e.printStackTrace();
    }
    // this block will give the response of upload link
    try {
        BufferedReader rd = new BufferedReader(new InputStreamReader(
            conn.getInputStream()));
        String line;
        while ((line = rd.readLine()) != null) {
        System.out.println("RESULT Message: " + line);
        }
        rd.close();
    } catch (IOException ioex) {
        Log.e("Huzza", "error: " + ioex.getMessage(), ioex);
    }
    return; // like 200 (Ok)

    

将图像上传到服务器工作正常。我需要将 mp3 文件和图像上传到服务器。

My code for uploading image to server is :

String userIdParameter = String.valueOf(userId);
    String fileName = "temporary_holder.jpg";
    HttpURLConnection conn = null;
    DataOutputStream dos = null;

    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;

    String sourceFileUri = HomeScreen.get_path();
    String upLoadServerUri = "http://10.120.10.87:8080/WebImage/UploadImage";

    File sourceFile = new File(sourceFileUri);
    if (!sourceFile.isFile()) {
        Log.e("Huzza", "Source File Does not exist");
        return;
    }
    int serverResponseCode = 0;
    try {

        // open a URL connection to the Servlet
        FileInputStream fileInputStream = new FileInputStream(sourceFile);

        // ------------------ CLIENT REQUEST
        URL url = new URL(upLoadServerUri);

        // Open a HTTP connection to the URL
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true); // Allow Inputs
        conn.setDoOutput(true); // Allow Outputs
        conn.setUseCaches(false); // Don't use a Cached Copy

        // Use a post method.
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");

        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type",
            "multipart/form-data;boundary=" + boundary);
        conn.setRequestProperty("file_name", fileName);
        conn.setRequestProperty("file_name_audio", fileName);
        conn.setRequestProperty("X-myapp-param1", userIdParameter);

        // conn.setFixedLengthStreamingMode(1024);
        // conn.setChunkedStreamingMode(1);

        dos = new DataOutputStream(conn.getOutputStream());

        dos.writeBytes(twoHyphens + boundary + lineEnd);

        dos.writeBytes("Content-Disposition: form-data; name=\"file_name\";filename=\""
            + fileName + "\"" + lineEnd);

        dos.writeBytes(lineEnd);
        
        
            // create a buffer of maximum size
        bytesAvailable = fileInputStream.available();

        int streamSize = (int) sourceFile.length();
        bufferSize = streamSize / 10;

        System.out.println("streamSize" + streamSize);

        buffer = new byte[streamSize];

        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        int count = 0;
        while (bytesRead > 0) {
        progress = (int) (count);
        displayNotification();
        Thread.sleep(500);
        
        dos.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        // bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        count += 10;

        }

        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        // Responses from the server (code and message)
        serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();

        System.out.println("Upload file to serverHTTP Response is : "
            + serverResponseMessage + ": " + serverResponseCode);
        // close streams
        System.out.println("Upload file to server" + fileName
            + " File is written");
        fileInputStream.close();
        dos.flush();
        dos.close();
    } catch (MalformedURLException ex) {
        ex.printStackTrace();
        Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
    } catch (Exception e) {
        e.printStackTrace();
    }
    // this block will give the response of upload link
    try {
        BufferedReader rd = new BufferedReader(new InputStreamReader(
            conn.getInputStream()));
        String line;
        while ((line = rd.readLine()) != null) {
        System.out.println("RESULT Message: " + line);
        }
        rd.close();
    } catch (IOException ioex) {
        Log.e("Huzza", "error: " + ioex.getMessage(), ioex);
    }
    return; // like 200 (Ok)

    

Uploading image to server works fine. I need to upload both mp3 file and image to the server.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甜味超标? 2024-11-10 02:17:03

那么,您想在一个 HTTP 请求中发送多个文件吗?我自己从未这样做过,但根据 RFC,只需添加另一个将正文添加到发送音频的消息中,它应该如下所示:

    dos = new DataOutputStream(conn.getOutputStream());
    dos.writeBytes(twoHyphens + boundary + lineEnd);
    dos.writeBytes("Content-Disposition: form-data; name=\"file_name\";filename=\""
        + fileName + "\"" + lineEnd);
    dos.writeBytes(lineEnd);
    // Code for sending the image....
    dos.writeBytes(lineEnd);


    dos.writeBytes(twoHyphens + boundary + lineEnd);
    dos.writeBytes("Content-Disposition: form-data; name=\"file_name_audio\";filename=\""
        + fileNameAudio + "\"" + lineEnd);
    dos.writeBytes(lineEnd);
    // Code for sending the MP3
    dos.writeBytes(lineEnd);
    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

确保两个部分的名称不同(取决于服务器软件)。

So, you want to send multiple files in one HTTP request? I've never done this myself, but according to the RFC, just add another body to the message in which you send the audio, it should look something like this:

    dos = new DataOutputStream(conn.getOutputStream());
    dos.writeBytes(twoHyphens + boundary + lineEnd);
    dos.writeBytes("Content-Disposition: form-data; name=\"file_name\";filename=\""
        + fileName + "\"" + lineEnd);
    dos.writeBytes(lineEnd);
    // Code for sending the image....
    dos.writeBytes(lineEnd);


    dos.writeBytes(twoHyphens + boundary + lineEnd);
    dos.writeBytes("Content-Disposition: form-data; name=\"file_name_audio\";filename=\""
        + fileNameAudio + "\"" + lineEnd);
    dos.writeBytes(lineEnd);
    // Code for sending the MP3
    dos.writeBytes(lineEnd);
    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

Make sure that the names of both parts are different (depending on the server software).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文