gpt4 book ai didi

java - JERSEY 使用 jquery/AJAX 上传文件

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:01:42 26 4
gpt4 key购买 nike

我想通过 jquery/AJAX 上传带有 Jersey 的文件,但我不知道如何从输入中获取文件并使用 ajax 发送它。

到目前为止,这是我的代码:

html

<form action="rest/files/upload" method="post" enctype="multipart/form-data">

<p>
Select a file : <input type="file" name="file" size="50" />
</p>

<input type="submit" value="Upload It" />
</form>

JAVA

    @POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
@FormDataParam("file") InputStream fileInputStream,
@FormDataParam("file") FormDataContentDisposition contentDispositionHeader) {

String filePath = SERVER_UPLOAD_LOCATION_FOLDER + contentDispositionHeader.getFileName();

// save the file to the server
saveFile(fileInputStream, filePath);

String output = "File saved to server location : " + filePath;

return Response.status(200).entity(output).build();

}

// save uploaded file to a defined location on the server
private void saveFile(InputStream uploadedInputStream,
String serverLocation) {

try {
OutputStream outpuStream = new FileOutputStream(new File(serverLocation));
int read = 0;
byte[] bytes = new byte[1024];

outpuStream = new FileOutputStream(new File(serverLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
outpuStream.write(bytes, 0, read);
}
outpuStream.flush();
outpuStream.close();
} catch (IOException e) {

e.printStackTrace();
}

}

该代码与正常的 html 提交一起工作。

我用了这个例子:jersey file upload

这是我目前的方法

var file = $('input[name="file"').get(0).files[0];

var formData = new FormData();
formData.append('file', file);

$.ajax({
url : '/OIS/rest/upload', //Server script to process data
type : 'POST',
data : formData,
cache : false,
contentType : 'multipart/form-data',
dataType : 'application/json',
processData : false,
success : function(data, textStatus, jqXHR) {
var userObj = JSON.parse(jqXHR.responseText);
alert(userObj);
},
error : function(jqXHR, textStatus, errorThrown) {
alert(textStatus);

}
});

但是它抛出了空指针异常

   Jan 31, 2015 12:51:46 PM org.apache.catalina.core.StandardWrapperValve invoke
SCHWERWIEGEND: Servlet.service() for servlet [Smart_Office] in context with path [/Smart_Office] threw exception
java.lang.NullPointerException
at com.sun.jersey.multipart.impl.MultiPartReaderClientSide.unquoteMediaTypeParameters(MultiPartReaderClientSide.java:244)
at com.sun.jersey.multipart.impl.MultiPartReaderClientSide.readMultiPart(MultiPartReaderClientSide.java:171)
at com.sun.jersey.multipart.impl.MultiPartReaderServerSide.readMultiPart(MultiPartReaderServerSide.java:80)
at com.sun.jersey.multipart.impl.MultiPartReaderClientSide.readFrom(MultiPartReaderClientSide.java:157)
at com.sun.jersey.multipart.impl.MultiPartReaderClientSide.readFrom(MultiPartReaderClientSide.java:85)
at com.sun.jersey.spi.container.ContainerRequest.getEntity(ContainerRequest.java:490)
at com.sun.jersey.spi.container.ContainerRequest.getEntity(ContainerRequest.java:555)
at com.sun.jersey.multipart.impl.FormDataMultiPartDispatchProvider$FormDataInjectableValuesProvider.getInjectableValues(FormDataMultiPartDispatchProvider.java:122)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$EntityParamInInvoker.getParams(AbstractResourceMethodDispatchProvider.java:153)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:203)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:540)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:715)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

最佳答案

你的服务器端源代码接缝是明智的,因为你已经遵循了一篇写得很好的教程,但是当你试图混合来自这篇文章和那篇文章的代码来带来一个 Ajaxified Upload with Jersey 示例时,这不会无缝地工作。

我要注意的主要问题是服务器端端点和客户端代码之间的内容协商。

我不会进入 Jersey 内部并寻找如何抛出 NPE 但我会建议更新您的客户端 Ajax 调用以省略 contentType 处理,将以下属性设置为 false :

  • 内容类型
  • 处理数据

并省略 dataType 属性,因此生成的代码如下所示:

var file = $('input[name="file"').get(0).files[0];
var formData = new FormData();
formData.append('file', file);
$.ajax({
url : '/OIS/rest/upload',
type : 'POST',
data : formData,
cache : false,
contentType : false,
processData : false,
success : function(data, textStatus, jqXHR) {
var userObj = JSON.parse(jqXHR.responseText);
alert(userObj);
},
error : function(jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});

关于java - JERSEY 使用 jquery/AJAX 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28251017/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com