有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

API调用中文件扩展名的java HTTP头参数

是否可以将文件扩展名添加到HTTP头中

我开发了一个使用API调用发送文件的程序。 该文件将不限于。doc。pdf,可以与一起使用。exe。zip扩展

该文件已成功上载到服务器,但文件扩展名似乎不正确,它显示的文件类型为data,而我期待的是另一种文件类型

下面是上传部分的示例代码源:

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://ServerName:Port/Anything/data");  //remote API URL 
String filepath = "C://User//test//";
String file1 = filepath.concat(file);
System.out.println("Sending the file");
FileBody bin = new FileBody(new File(file1));  // take the file from directory 
HttpEntity reqEntity = MultipartEntityBuilder.create()
        .addPart("display_name", (ContentBody) bin)
        .build();
post.addHeader("filename", file1);  
post.setEntity(reqEntity);  // send via post method



文件正文也会读取文件扩展名吗


共 (2) 个答案

  1. # 1 楼答案

    为了指定文件类型,即Mime type,应该使用FielBody的2个参数或3个参数构造函数中的一个,而不是已经使用的一个参数构造函数

    根据您的文件类型,它应该如下所示:

    FileBody bin = new FileBody(new File(file1), ContentType.DEFAULT_BINARY);
    
  2. # 2 楼答案

    在编写本文时,您可以找到FileBodyon the relevant repo的三个构造函数的源代码

    public FileBody(final File file) {
        this(file, ContentType.DEFAULT_BINARY, file != null ? file.getName() : null);
    }
    
    /**
     * @since 4.3
     */
    public FileBody(final File file, final ContentType contentType, final String filename) {
        super(contentType);
        Args.notNull(file, "File");
        this.file = file;
        this.filename = filename == null ? file.getName() : filename;
    }
    
    /**
     * @since 4.3
     */
    public FileBody(final File file, final ContentType contentType) {
        this(file, contentType, file != null ? file.getName() : null);
    }
    

    如果不指定contentType,默认值为ContentType.DEFAULT_BINARY
    正是内容类型定义了“文件类型”,因为并非每个操作系统都使用文件扩展名


    如果在Linux系统中运行,请参阅How can I find out a files “mime-type(Content-Type?)”?以检索文件的mime类型
    还有一个Windows equivalent question

    contentType中拥有内容类型后,请使用正确的构造函数:new FileBody(new File(file1), ContentType.create(contentType));
    您可能还想添加编码信息,请参见ContentType


    您没有指定正在运行的服务器,但在开始检测文件的mime类型之前,您可以做一个快速测试,将硬编码的mime类型放入请求中
    只需将FileBody对象构造为

    FileBody bin = new FileBody(new File(file1), ContentType.create("image/png"));