如何使用JSP/Servlet上传文件到服务器?
我试了一下:
<form action="upload" method="post">
<input type="text" name="description" />
<input type="file" name="file" />
<input type="submit" />
</form>
但是,我只得到了文件名,而不是文件内容。当我添加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.
不幸的是,servlet抛出了一个异常,没有明确的消息和原因。下面是stacktrace:
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 org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:637)
首先你必须将表单的enctype属性设置为"multipart/form-data"
如下所示。
<form action="Controller" method="post" enctype="multipart/form-data">
<label class="file-upload"> Click here to upload an Image </label>
<input type="file" name="file" id="file" required>
</form>
然后,在Servlet“控制器”中添加用于多部分的注释,以指示在Servlet中处理多部分数据。
完成此操作后,检索通过表单发送的部分,然后检索提交文件的文件名(带路径)。使用它在所需的路径中创建一个新文件,并将文件的部分写入新创建的文件以重新创建该文件。
如下图所示:
@MultipartConfig
public class Controller extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
insertImage(request, response);
}
private void addProduct(HttpServletRequest request, HttpServletResponse response) {
Part filePart = request.getPart("file");
String imageName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
String imageSavePath = "specify image path to save image"; //path to save image
FileOutputStream outputStream = null;
InputStream fileContent = null;
try {
outputStream = new FileOutputStream(new File(imageSavePath + File.separator + imageName));
// Creating a new file with file path and the file name
fileContent = filePart.getInputStream();
// Getting the input stream
int readBytes = 0;
byte[] readArray = new byte[1024];
// Initializing a byte array with size 1024
while ((readBytes = fileContent.read(readArray)) != -1) {
outputStream.write(readArray, 0, readBytes);
} // This loop will write the contents of the byte array unitl the end to the output stream
} catch (Exception ex) {
System.out.println("Error Writing File: " + ex);
} finally {
if (outputStream != null) {
outputStream.close();
// Closing the output stream
}
if (fileContent != null) {
fileContent.close();
// Closing the input stream
}
}
}
}
您可以使用JSP /servlet上传文件。
<form action="UploadFileServlet" method="post">
<input type="text" name="description" />
<input type="file" name="file" />
<input type="submit" />
</form>
另一方面,在服务器端,使用以下代码。
package com.abc..servlet;
import java.io.File;
---------
--------
/**
* Servlet implementation class UploadFileServlet
*/
public class UploadFileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public UploadFileServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.sendRedirect("../jsp/ErrorPage.jsp");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
HttpSession httpSession = request.getSession();
String filePathUpload = (String) httpSession.getAttribute("path") != null ? httpSession.getAttribute("path").toString() : "" ;
String path1 = filePathUpload;
String filename = null;
File path = null;
FileItem item = null;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
String FieldName = "";
try {
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
item = (FileItem) iterator.next();
if (fieldname.equals("description")) {
description = item.getString();
}
}
if (!item.isFormField()) {
filename = item.getName();
path = new File(path1 + File.separator);
if (!path.exists()) {
boolean status = path.mkdirs();
}
/* Start of code fro privilege */
File uploadedFile = new File(path + Filename); // for copy file
item.write(uploadedFile);
}
} else {
f1 = item.getName();
}
} // END OF WHILE
response.sendRedirect("welcome.jsp");
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
如果你碰巧使用Spring MVC,这是如何(我把它留在这里,以防有人发现它有用):
使用一个enctype属性设置为"multipart/form-data"的表单(与BalusC的答案相同):
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload"/>
</form>
在控制器中,将请求参数文件映射为MultipartFile类型,如下所示:
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void handleUpload(@RequestParam("file") MultipartFile file) throws IOException {
if (!file.isEmpty()) {
byte[] bytes = file.getBytes(); // alternatively, file.getInputStream();
// application logic
}
}
你可以使用MultipartFile的getOriginalFilename()和getSize()来获取文件名和大小。
我已经用Spring版本4.1.1.RELEASE测试了这个功能。
对于Spring MVC
我设法有一个更简单的版本,用于获取表单输入,包括数据和图像。
<form action="/handleform" method="post" enctype="multipart/form-data">
<input type="text" name="name" />
<input type="text" name="age" />
<input type="file" name="file" />
<input type="submit" />
</form>
要处理的控制器
@Controller
public class FormController {
@RequestMapping(value="/handleform",method= RequestMethod.POST)
ModelAndView register(@RequestParam String name, @RequestParam int age, @RequestParam MultipartFile file)
throws ServletException, IOException {
System.out.println(name);
System.out.println(age);
if(!file.isEmpty()){
byte[] bytes = file.getBytes();
String filename = file.getOriginalFilename();
BufferedOutputStream stream =new BufferedOutputStream(new FileOutputStream(new File("D:/" + filename)));
stream.write(bytes);
stream.flush();
stream.close();
}
return new ModelAndView("index");
}
}
在Tomcat 6或Tomcat 7中没有组件或外部库
在web.xml文件中启用上传:
手动安装PHP、Tomcat和Httpd Lounge。
<servlet>
<servlet-name>jsp</servlet-name>
<servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
<multipart-config>
<max-file-size>3145728</max-file-size>
<max-request-size>5242880</max-request-size>
</multipart-config>
<init-param>
<param-name>fork</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>xpoweredBy</param-name>
<param-value>false</param-value>
</init-param>
<load-on-startup>3</load-on-startup>
</servlet>
如你所见:
<multipart-config>
<max-file-size>3145728</max-file-size>
<max-request-size>5242880</max-request-size>
</multipart-config>
使用JSP上传文件。文件:
在HTML文件中
<form method="post" enctype="multipart/form-data" name="Form" >
<input type="file" name="fFoto" id="fFoto" value="" /></td>
<input type="file" name="fResumen" id="fResumen" value=""/>
在JSP文件或Servlet中
InputStream isFoto = request.getPart("fFoto").getInputStream();
InputStream isResu = request.getPart("fResumen").getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte buf[] = new byte[8192];
int qt = 0;
while ((qt = isResu.read(buf)) != -1) {
baos.write(buf, 0, qt);
}
String sResumen = baos.toString();
编辑您的代码以满足servlet的要求,如max-file-size, max-request-size和其他选项,您可以设置…