4

I've been all day trying to make the client send AJAX requests with UTF-8 encoding in FormData() objects. I'm using Sping MVC on the server side, but that doesn't apply in this case, since:

  1. I can POST to the server non-multipart requests, and I can capture the request and see:

    Content-Type: application/x-www-form-urlencoded; charset=UTF-8
    

    and I also can see the characters encoded OK (á, é, í, ó, ú).

  2. If I POST using AJAX + file upload + FormData, using the following code:

    var data = new FormData();
    data.append('body', jq("#sp_body").val());
    data.append('signature', jq("#sp_signature").val());
    data.append('subject', jq("#sp_subject").val());
    data.append('email', jq("#sp_email").val());
    data.append("file", jq("#sp_file")[0].files[0]);
    jq.ajax({
        url: contextPath + "/jobs/" + job + "/sendmail",
        data: data,
        cache: false,
        dataType: 'text',
        processData: false,
        contentType: false,
        mimeType: "multipart/form-data",
        type: 'POST',
        success: function(result){
            data = jq.parseJSON(result);
            if (data["statusCode"] == "success") {
                jq("#save_status").html("Email sent!").show().delay(5000).fadeOut(200);
            } else {
                jq("#save_status").html(data["errors"]).show().delay(5000).fadeOut(200);
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
        }
    });
    

    Then I capture the request and I see:

    Content-Type: multipart/form-data; boundary=---------------------------279972256522979
    

    But no UTF-8 in the header, and the non-latin characters are garbled.

The question is, how can I POST using FormData (since I want to POST strings and a file at the same time), having UTF-8 encoding set?

I've read UTF-8 text is garbled when form is posted as multipart/form-data but that didn't help me.

Community
  • 1
  • 1
Azurlake
  • 612
  • 1
  • 6
  • 29
  • possible duplicate of [Uploading both data and files in one form using Ajax?](http://stackoverflow.com/questions/10899384/uploading-both-data-and-files-in-one-form-using-ajax) – DallaRosa Feb 26 '14 at 00:43
  • @DallaRosa Nope, I've read all 30-40 topics about the question, none of them helped me to solve the problem, and the topic you point at it's just about sending both things in a single AJAX request, which I'm already doing "successfully", except for the encoding. The HTTP page has also the meta header setting `charset=utf-8`. – Azurlake Feb 26 '14 at 11:15

1 Answers1

2

In your servlet, you have to set the encoding again:

public void extractRequest(HttpServletRequest request) throws Exception {
    if (request != null) {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = null;
            try {
                items = upload.parseRequest(request);
            }
            catch (FileUploadException e) {
                e.printStackTrace();
            }
            while (itr.hasNext()) {
                FileItem item = itr.next();
                if (item.isFormField()) {
                    String name = item.getFieldName();
                    String value = item.getString("UTF-8");
                ...
                ...

In your html:

<form id="formid" action="<yourpath>" enctype="multipart/form-data" 
method="POST" accept-charset="utf-8">

And of course, if you are using a database, same thing has to be set there as well

Do let me know if this helps; otherwise we can look at other areas.

George
  • 6,006
  • 6
  • 48
  • 68
  • Thanks for the answer. I finally made it work. Do you know what the problem was? Well, when I deployed the app on the server, everything worked as expected. It turns out that the Eclipse IDE + Tomcat tandem under Windows that was causing trouble (couldn't find the exact reason, as I took the time to have a look and change wherever needed the config files), but when I deployed the WAR on the server, everything went OK. – Azurlake Apr 27 '14 at 10:48
  • Great to hear it's working, and thanks for sharing your solution here :) – George Apr 27 '14 at 12:05