apache HttpClient, upload a file via form: use StringBody instead of FileBody

A web server expects a file to be uploaded via an html form.

This is the way how i construct the MultipartEntity, that already works:

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

The fact is that i have my data in memory, so i don't like the idea of saving it to disk, and so I've tried to replace

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

with

StringBody filePart = new StringBody("");    

But the second way doesn't work, the server returns a HTTP 500 exception; logging the data on the wire, i noticed that the only difference is as follows:

HTTP POST trace when FileBody has been used:

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

HTTP POST trace when StringBody has been used:

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

That is, in the FileBody upload, it is specified a "filename" that is not specified in the StringBody upload. How can i fix this?


With a StringBody you won't be able to set a filename. But you can extend StringBody and override getFilename() to not return null .

According to the sources for FormBodyPart , this should be enough to have the desired filename-parm parameter:

 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());
 }

只是放弃这一点,因为我有这个问题,并继续在我的搜索到这里...类似于上面的方法,但我想它更简单。

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;
    }
}
链接地址: http://www.djcxy.com/p/22186.html

上一篇: 从java客户端上传文件到apache http服务器

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