JavaFX:由于缺少边界,文件上载到REST服务/ servlet失败

时间:2010-04-21 19:29:20

标签: file-upload javafx multipart

我正在尝试使用HttpRequest使用JavaFX上传文件。为此我写了以下函数。

function uploadFile(inputFile : File) : Void {
    // check file
    if (inputFile == null or not(inputFile.exists()) or inputFile.isDirectory()) {
        return;
    }    
    def httpRequest : HttpRequest = HttpRequest {
        location: urlConverter.encodeURL("{serverUrl}");
        source: new FileInputStream(inputFile)
        method: HttpRequest.POST
        headers: [
            HttpHeader {
                name: HttpHeader.CONTENT_TYPE
                value: "multipart/form-data"
            }
        ]
    }
    httpRequest.start();
}

在服务器端,我正在尝试使用Jersey REST服务使用Apache Commons FileUpload API处理传入数据。用于执行此操作的代码是Apache主页上的FileUpload教程的简单副本。

@Path("Upload")
public class UploadService {

  public static final String RC_OK = "OK";
  public static final String RC_ERROR = "ERROR";

  @POST
  @Produces("text/plain")
  public String handleFileUpload(@Context HttpServletRequest request) {
    if (!ServletFileUpload.isMultipartContent(request)) {
      return RC_ERROR;
    }
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> items = null;
    try {
      items = upload.parseRequest(request);
    } 
    catch (FileUploadException e) {
      e.printStackTrace();
      return RC_ERROR;
    }
    ...
  }
}   

但是,我在items = upload.parseRequest(request);获得了例外: org.apache.commons.fileupload.FileUploadException:请求被拒绝,因为没有找到多部分边界

我想我必须向InputStream添加手动边界信息。这有什么简单的解决方案吗?还是有其他解决方案吗?

1 个答案:

答案 0 :(得分:3)

您是否尝试过使用InputStream中的HttpServletRequest

InputStream is = httpRequest.getInputStream();
BufferedInputStream in = new BufferedInputStream(is);
//Write out bytes

out.close();
is.close();