我正在使用此代码上传文件
@Path(value= "/up")
public class upload {
public static String SERVER_UPLOAD_LOCATION_FOLDER = "C://Users/Marya/Desktop/";
@POST
@Path(value="upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(@FormDataParam("file") InputStream fileInputStream,@FormDataParam("name") FormDataContentDisposition fileDetail) {
String filePath = SERVER_UPLOAD_LOCATION_FOLDER + fileDetail.getFileName();
System.out.println("*****serverpath********");
saveFile(fileInputStream, filePath);
String output = "File saved to server location : " + filePath;
System.out.println("done");
return Response.status(200).entity(output).build();
}
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);
System.out.println("*****read********");
}
outpuStream.flush();
outpuStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
此代码正常运行,但上传文件的名称为“newfile”,如路径“C:// Users / Marya / Desktop / newfile”中所述。那么如何按名称保存文件呢?
添加jar后我收到此错误
新错误
Grave: The RuntimeException could not be mapped to a response, re-throwing to the HTTP container
java.lang.NullPointerException
at com.example.upload.uploadFile(upload.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205)
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:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
答案 0 :(得分:1)
您应该在帖子中传递文件名:
@Path(value= "/up")
public class upload {
public static String SERVER_UPLOAD_LOCATION_FOLDER = "C://Users//Marya//Desktop//newfile";
@POST
@Path(value="upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile( @FormDataParam("file") InputStream fileIS, @FormDataParam("name") String name ) {
//recommand to test call arguments here (null, empty) in order to throw errors
if (name==null || fileIS==null) return Response.status(400).build();
String location =SERVER_UPLOAD_LOCATION_FOLDER+java.io.File.separator+ name;
System.out.println("before write ["+location+"]");
saveFile(fileIS, location );
String output = "File saved to server location : " + location;
System.out.println("file written ["+location+"]");
return Response.ok().entity(output).build();
}
/**
**/
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);
System.out.println("*****read********");
}
outpuStream.flush();
outpuStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
要写一个漂亮的代码,我应该使用org.apache.commons.io.IOUtils.write()
,这比执行自己的循环读取/写入要好得多。这将重构saveFile():
/**
* save File v2 with apache.commons.io
**/
private void saveFile(InputStream uploadedInputStream,String serverLocation) {
try {
OutputStream outpuStream = new FileOutputStream(new File(serverLocation));
org.apache.commons.io.IOUtils.write(uploadedInputStream, outpuStream );
outpuStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
享受! :)
更新于6/06 12:23 BRT 请尝试以下代码:
@Path(value= "/up")
public class upload {
public static String SERVER_UPLOAD_LOCATION_FOLDER = "C://Users//Marya//Desktop//newfile";
@POST
@Path(value="upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile( @FormDataParam("file") InputStream fileIS, @FormDataParam("file") FormDataContentDisposition fileDetail ) {
//recommand to test call arguments here (null, empty) in order to throw errors
if (fileDetail ==null || fileIS==null) return Response.status(400).build();
String location =SERVER_UPLOAD_LOCATION_FOLDER+java.io.File.separator+ fileDetail.getFileName();
System.out.println("before write ["+location+"]");
saveFile(fileIS, location );
String output = "File saved to server location : " + location;
System.out.println("file written ["+location+"]");
return Response.ok().entity(output).build();
}
更新于6/06 14:54 BRT 请尝试以下代码:
@Path(value= "/up")
public class upload {
public static String SERVER_UPLOAD_LOCATION_FOLDER = "C://Users//Marya//Desktop//newfile";
@POST
@Path(value="upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile( @FormDataParam("file") InputStream fileIS, @FormDataParam("file") FormDataContentDisposition fileDetail ) {
//recommand to test call arguments here (null, empty) in order to throw errors
if (fileDetail ==null || fileIS==null) return Response.status(400).build();
String location =SERVER_UPLOAD_LOCATION_FOLDER+java.io.File.separator+ fileDetail.getFileName();
System.out.println("before write ["+location+"]");
saveFile(fileIS, location );
String output = "File saved to server location : " + location;
System.out.println("file written ["+location+"]");
return Response.status(200).entity(output).build();
}