apache HttpClient,通过表单上传文件:使用StringBody而不是FileBody

时间:2012-12-26 10:46:50

标签: java http httpclient

Web服务器希望通过html表单上传文件。

这就是我构建已经有效的MultipartEntity的方式:

FileBody filePart = new FileBody(new File("emptyFile.txt"), "text/plain");
FormBodyPart fbp = new FormBodyPart("UploadService", filePart);
MultipartEntity mpe = new MultipartEntity();  
mpe.addPart(fbp);

事实是我的数据存储在内存中,所以我不喜欢将其保存到磁盘的想法,所以我试图替换

FileBody filePart = new FileBody(new File("emptyFile.txt"), "text/plain");

StringBody filePart = new StringBody("");    

但是第二种方法不起作用,服务器返回HTTP 500异常;在线上记录数据,我注意到唯一的区别如下:

使用FileBody时的HTTP POST跟踪:

...
Content-Disposition: form-data; name="UploadService"; filename="emptyFile.txt"
...

使用StringBody时的HTTP POST跟踪:

...
Content-Disposition: form-data; name="UploadService"
...

也就是说,在FileBody上传中,指定了一个未在StringBody上传中指定的“文件名”。 我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

使用StringBody,您将无法to set a filename。但您可以延长StringBody并覆盖getFilename()以不返回null

根据FormBodyPart的来源,这应该足以拥有所需的filename-parm参数:

 protected void generateContentDisp(final ContentBody body) {
     StringBuilder buffer = new StringBuilder();
     buffer.append("form-data; name=\"");
     buffer.append(getName());
     buffer.append("\"");
     if (body.getFilename() != null) {
         buffer.append("; filename=\"");
         buffer.append(body.getFilename());
         buffer.append("\"");
     }
     addField(MIME.CONTENT_DISPOSITION, buffer.toString());
 }

答案 1 :(得分:0)

刚刚把这个放在这里,因为我遇到了这个问题而且一直在我的搜索中出现......与上面的方法类似,但我想它更简单。

public class StringFileBody extends FileBody {

    private String data;

    public StringFileBody( String input, ContentType contentType ) {

        super( new File( "." ), contentType );

        data = input;
    }

    public StringFileBody( String input, ContentType contentType, String fileName ) {

        super( new File( "." ), contentType, fileName );

        data = input;
    }

    @Override
    public void writeTo( OutputStream out ) throws IOException {

        out.write( data.getBytes( ) );
    }

    @Override
    public long getContentLength( ) {

        return data.getBytes( ).length;
    }
}
相关问题