Javascript 将文件上载到Spark API端点
我正在尝试使用和enpoint将文件上载到Spark Api,如下所示:Javascript 将文件上载到Spark API端点,javascript,java,rest,fetch,spark-java,Javascript,Java,Rest,Fetch,Spark Java,我正在尝试使用和enpoint将文件上载到Spark Api,如下所示: after((Filter) (request, response) -> { response.header("Access-Control-Allow-Origin", "*"); response.header("Access-Control-Allow-Methods", "POST"); }); post("/scene", (request, response) -> {
after((Filter) (request, response) -> {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Methods", "POST");
});
post("/scene", (request, response) -> {
Path tempFile = Files.createTempFile(uploadDir.toPath(), "", "");
request.attribute("org.eclipse.jetty.multipartConfig", new MultipartConfigElement("/temp"));
try (InputStream is = request.raw().getPart("uploaded_file").getInputStream()) {
Files.copy(is, tempFile, StandardCopyOption.REPLACE_EXISTING);
DAOIntf dao = new DAO(tempFile.toAbsolutePath().toString(),"map.xml");
Scene scene = dao.getXmlScene();
return new Gson().toJson(scene);
}catch (Exception e){
return e;
}
});
通过使用React应用程序中的fetch,如下所示:
handleFileChange(e) {
e.preventDefault();
let fileInput = document.getElementsByName("uploaded_file")[0];
fetch(apiAddress, {
method: 'POST',
body: fileInput.files[0]
}).then( (res) => {
return res.json()
}).then( (res) => {
this.props.onFileChange(JSON.stringify(res));
});
}
我知道API正在工作,因为我用简单的html表单尝试了它。所以我猜问题与我如何构建有效载荷有关
我收到的是404,服务器上的消息记录如下:
INFO spark.http.matching.MatcherFilter-请求的路由[/scene]尚未映射到spark中
这是我要寄的包裹
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: es-ES,es;q=0.9,en;q=0.8,en-GB;q=0.7
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Connection: keep-alive
Host: localhost:4567
Origin: http://localhost:3000
Referer: http://localhost:3000/
--更新--
Im使用此组件激活呼叫:
render(){ return (
<form>
<input type='file' name='uploaded_file' ref={input => {
this.fileInput = input;
}}/>
<button onClick={this.handleFileChange}>Upload</button> </form> ) }
render(){return(
{
this.fileInput=输入;
}}/>
上传)}
如果我在不选择文件的情况下使用它,我会得到一个OK 200和一个
javax.servlet.ServletException:Content Type!=服务器中的多部分/表单数据
异常。因此,沟通是有效的。现在仍然不知道问题出在哪里。如果在使用curl时调用了/scene
路由处理程序,但在使用react的fetch时没有调用,这意味着它映射正确,但发送post请求的方式不同。所以我想试着理解它的不同之处(标题等)。对不起,我弄错了,它不适用于curl。