如何使用JSP/Servlet将文件上传到服务器?我试过这个:
<form action="upload" method="post">
<input type="text" name="description" />
<input type="file" name="file" />
<input type="submit" />
</form>
Run Code Online (Sandbox Code Playgroud)
但是,我只获取文件名,而不是文件内容.当我添加 enctype="multipart/form-data"到<form>,然后request.getParameter()返回null.
在研究期间,我偶然发现了Apache Common FileUpload.我试过这个:
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request); // This line is where it died.
Run Code Online (Sandbox Code Playgroud)
不幸的是,servlet抛出了一个没有明确消息和原因的异常.这是堆栈跟踪:
SEVERE: Servlet.service() for servlet UploadServlet threw exception
javax.servlet.ServletException: Servlet execution threw an exception
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:313)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at …Run Code Online (Sandbox Code Playgroud) 我一直在寻找这个,没有什么对我有用.
我正在尝试将图像从Android应用程序上传到java servlet并将其保存在服务器中.我找到的每个解决方案都不适用于我.
我的代码目前做了什么:android应用程序将图像发送到servlet,当我试图保存它时,文件被创建,但它是空的:(
谢谢你的帮助!
我在android客户端的代码(i_file是设备上的文件位置):
public static void uploadPictureToServer(String i_file) throws ClientProtocolException, IOException {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("http://192.168.1.106:8084/Android_Server/GetPictureFromClient");
File file = new File(i_file);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown(); …Run Code Online (Sandbox Code Playgroud)