2

We're trying to upload a song (.mp3) file from a JSP frontend written in HTML / Javascript. We need to upload to our Java backend using websockets. Does anyone have any suggestions on how we would could go about doing this?

Currently we are doing something like this on our JSP file:

    <h1>Please Choose a Song file</h1>
    <form name = "JSONUploadForm">
        <input type = "file" name="file" accept = ".mp3"/> <br/>
        <input type = "button" value = "Click to upload!" name = "button" onClick = "submitSong();"/>
    </form>

Then we have our javascript function submitSong()

function submitSong(){
    var songStuffs = document.getElementById("file");
    console.log(songStuffs); --> we get "null" here
    sendMessage(songStuffs);
    alert("song sent");
}


function sendMessage(val, string) {
    socket.send(string);
    return false;
}

Also, here is our connect to server function. However, this functions correctly.

function connectToServer() {
    socket = new 
    WebSocket("ws://localhost:8080/Project/socket");
    socket.onopen = function(event) {
    console.log("connected!");
}

You can also see our server side (.java file):

@OnMessage
public void onMessage(String message, Session session) throws IOException, EncodeException {
        FileWriter fw = new FileWriter(new File(songName + ".mp3"));
        fw.write(song);

        BufferedReader fr = new BufferedReader(new FileReader(songName + ".mp3"));
        String data = fr.readLine();

        System.out.println("Song: " + data); --> Here we get "song: null"
}

Any suggestions would be greatly appreciated!

2 Answers2

1

In your code you have an error

"var songStuffs = document.getElementById("file");"

Your file input without id. this will work "var songStuffs = document.querySelector("[name=file]");"

I prefer using querySelector, because it mo flexeble and works exactly like jquery query selectors)))

You do not need any form, for upload files. Please read this article https://www.html5rocks.com/en/tutorials/websockets/basics/, it will be useful for you (search words "blob" at the page)

Html

<input id="file" type = "file" name="file" accept = ".mp3"/>

Code

var fileInput = document.querySelector("#file");
fileInput.addEventListener("change",function(){
   connection.send(fileInput.files[0]);
}); 

If you need to send file and fields, you have 3 variants

  1. create JSON {"field1":"value1","field2":"value1", "file":"base64"}
  2. manualy create formdata and parse form data at the server with some webform stuff (example https://stackoverflow.com/a/47279216/5138198)
  3. Firstly send JSON data, secondly send a file
Alex Nikulin
  • 8,194
  • 4
  • 35
  • 37
0

Try with this, If you have to upload file you should add enctype in form.

<form enctype="multipart/form-data">
      <input type = "file" name="file" id="song" accept = ".mp3"/>
</form>

Update:

You can use simply WebSocketFileTransfer plugin to send your file. This plugin helps in with many features like Auth, progress status, file/blob compatibility.

var songStuffs = document.getElementById("song").files[0];
var transfer = new WebSocketFileTransfer({
    url: 'ws://ip:port/path/to/upload_web_socket_server',
    file: songStuffs,
    progress: function(event) {
        // Update the progress bar
    },
    success: function(event) {
        // Do something
    }
  });

transfer.start();
Vinoth Krishnan
  • 2,925
  • 6
  • 29
  • 34