且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

httpclient上传文件的文件名的中文问题

更新时间:2022-09-06 10:21:28

在利用httpclient向服务器post数据时,有两种中文问题;

 

1.filed字段值的中文

2.file名的中文

 

对于第一种,参看StringPart;其源代码有这样一段:

    private byte[] getContent() {
        if (content == null) {
            content = EncodingUtil.getBytes(value, getCharSet());
        }
        return content;
    }
    
    protected void sendData(OutputStream out) throws IOException {
        LOG.trace("enter sendData(OutputStream)");
        out.write(getContent());
    }

可以看出在发送数据时其调用了EncodingUtil的getBytes方法(利用了你通过setCharSet设置的编码)

因此,只要你在代码中这样:

   StringPart part = new StringPart(name, value);

   part.setCharSet("GBK");

中文就没有问题了

 

对于第二种,参看FilePart;其源代码中有这样一段:

protected void sendDispositionHeader(OutputStream out) 
    throws IOException {
        LOG.trace("enter sendDispositionHeader(OutputStream out)");
        super.sendDispositionHeader(out);
        String filename = this.source.getFileName();
        if (filename != null) {
            out.write(FILE_NAME_BYTES);
            out.write(QUOTE_BYTES);
            out.write(EncodingUtil.getAsciiBytes(filename));
            out.write(QUOTE_BYTES);
        }
    }

可以看出在转换文件名时,用的方法是EncodingUtil.getAsciiBytes(),查看这个方法源码为data.getBytes("US-ASCII"),因此中文文件名必定乱码,不管你是否调用了setCharSet("GBK")方法。

解决很简单:

   out.write(EncodingUtil.getBytes(filename, getCharSet()));

 

看了网上好多文章,好多都说改EncodingUtil类,其实我觉得改FilePart更好一些