解决HttpClient的FilePart上传文件中使用中文名称文件名乱码问题(需要重写方法)

2022-07-31 11:16:14

解决HttpClient的FilePart上传文件中使用中文名称文件名乱码问题,我当时在网上找了一遍,网上都是

public class CustomFilePart extends FilePart {     
    public CustomFilePart(String filename, File file)     
            throws FileNotFoundException {     
        super(filename, file);     
    }     
    
    protected void sendDispositionHeader(OutputStream out) throws IOException {     
        super.sendDispositionHeader(out);     
        String filename = getSource().getFileName();     
        if (filename != null) {     
            out.write(EncodingUtil.getAsciiBytes(FILE_NAME));     
            out.write(QUOTE_BYTES);     
            out.write(EncodingUtil.getBytes(filename, "utf-8"));     
            out.write(QUOTE_BYTES);     
        }     
    }     
}

直接用这个,传送过去的时候还是乱码,需要对其进行重写
下面是重写的代码

/**
 *解决中文文件名乱码
 */
public class CustomFilePart extends FilePart {
    public CustomFilePart(String filename, File file)
            throws FileNotFoundException {
        super(filename, file);
    }

    @Override
    protected void sendDispositionHeader(OutputStream out) throws IOException {
        out.write(CONTENT_DISPOSITION_BYTES);
        out.write(QUOTE_BYTES);
        out.write(EncodingUtils.getBytes(getName(), "utf-8"));
        out.write(QUOTE_BYTES);
        String filename = getSource().getFileName();
        if (filename != null) {
            out.write(EncodingUtil.getAsciiBytes(FILE_NAME));
            out.write(QUOTE_BYTES);
            out.write(EncodingUtil.getBytes(filename, "utf-8"));
            out.write(QUOTE_BYTES);
        }
    }
}```



重写后,上传的附件名才正确的显示出来
上传附件到法务系统返回的{
  "code" : "0",
  "msg" : "Success",
  "errMsg" : "Success",
  "timestamp" : "2020-03-24 11:39:14.423",
  "data" : {
    "fileId" : "1242294878479568897",
    "fileSize" : "195294",
    "fileName" : "重点强调:新员工入职(1).pdf"
  }
}
  • 作者:ouyang_x
  • 原文链接:https://blog.csdn.net/ouyang_x/article/details/105068235
    更新时间:2022-07-31 11:16:14