简体   繁体   中英

Sending files and text with AJAX + multipart form data + UTF-8 encoding

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM