如何使用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抛出异常而没有明确的消息和原因。这是堆栈跟踪:
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)
答案 0 :(得分:1141)
答案 1 :(得分:25)
如果您碰巧使用Spring MVC,这是如何: (我将此留在这里以防有人发现它有用)。
使用enctype
属性设置为&#34; multipart/form-data
&#34; (与BalusC的答案相同)
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload"/>
</form>
在您的控制器中,将请求参数file
映射到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
对此进行了测试。
答案 2 :(得分:12)
您需要将common-io.1.4.jar
文件包含在lib
目录中,或者如果您在任何编辑器(如NetBeans)中工作,那么您需要转到项目属性并添加JAR文件,你将完成。
要获取common.io.jar
文件只是谷歌它或只是去Apache Tomcat网站,您可以在其中获得免费下载此文件的选项。但请记住一件事:如果您是Windows用户,请下载二进制ZIP文件。
答案 3 :(得分:9)
我正在为每个 Html表单使用公共Servlet,无论它是否有附件。
此Servlet返回TreeMap
,其中键是jsp名称参数和值是用户输入并将所有附件保存在固定目录中,稍后您重命名所选目录.Here Connections是具有连接对象的自定义接口。我想这会对你有帮助
public class ServletCommonfunctions extends HttpServlet implements
Connections {
private static final long serialVersionUID = 1L;
public ServletCommonfunctions() {}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {}
public SortedMap<String, String> savefilesindirectory(
HttpServletRequest request, HttpServletResponse response)
throws IOException {
// Map<String, String> key_values = Collections.synchronizedMap( new
// TreeMap<String, String>());
SortedMap<String, String> key_values = new TreeMap<String, String>();
String dist = null, fact = null;
PrintWriter out = response.getWriter();
File file;
String filePath = "E:\\FSPATH1\\2KL06CS048\\";
System.out.println("Directory Created ????????????"
+ new File(filePath).mkdir());
int maxFileSize = 5000 * 1024;
int maxMemSize = 5000 * 1024;
// Verify the content type
String contentType = request.getContentType();
if ((contentType.indexOf("multipart/form-data") >= 0)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File(filePath));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax(maxFileSize);
try {
// Parse the request to get file items.
@SuppressWarnings("unchecked")
List<FileItem> fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator<FileItem> i = fileItems.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if (!fi.isFormField()) {
// Get the uploaded file parameters
String fileName = fi.getName();
// Write the file
if (fileName.lastIndexOf("\\") >= 0) {
file = new File(filePath
+ fileName.substring(fileName
.lastIndexOf("\\")));
} else {
file = new File(filePath
+ fileName.substring(fileName
.lastIndexOf("\\") + 1));
}
fi.write(file);
} else {
key_values.put(fi.getFieldName(), fi.getString());
}
}
} catch (Exception ex) {
System.out.println(ex);
}
}
return key_values;
}
}
答案 4 :(得分:8)
Tomcat 6 7中没有组件或外部库
在 web.xml 文件中启用上传:
<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 以及您可以设置的其他选项......
答案 5 :(得分:8)
对于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");
}
}
希望有所帮助:)
答案 6 :(得分:6)
如果您将Geronimo与其嵌入式Tomcat一起使用,则会出现此问题的另一个原因。在这种情况下,在测试commons-io和commons-fileupload的多次迭代之后,问题来自处理commons-xxx jar的父类加载器。必须防止这种情况。崩溃始终发生在:
fileItems = uploader.parseRequest(request);
请注意,fileItems的List类型已更改,当前版本的commons-fileupload具体为List<FileItem>
,而不是之前版本为List
的版本。
我将commons-fileupload和commons-io的源代码添加到我的Eclipse项目中以跟踪实际错误并最终得到一些见解。首先,抛出的异常是Throwable类型,而不是声明的FileIOException,甚至Exception(这些都不会被捕获)。其次,错误消息是混淆的,因为它声明找不到类,因为axis2找不到commons-io。 Axis2根本不在我的项目中使用,但作为标准安装的一部分存在于Geronimo存储库子目录中的文件夹中。
最后,我找到了一个提出成功解决问题的有效解决方案的地方。您必须在部署计划中隐藏来自父加载程序的jar。这被放入geronimo-web.xml,我的完整文件如下所示。
Pasted from <http://osdir.com/ml/user-geronimo-apache/2011-03/msg00026.html>
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<web:web-app xmlns:app="http://geronimo.apache.org/xml/ns/j2ee/application-2.0" xmlns:client="http://geronimo.apache.org/xml/ns/j2ee/application-client-2.0" xmlns:conn="http://geronimo.apache.org/xml/ns/j2ee/connector-1.2" xmlns:dep="http://geronimo.apache.org/xml/ns/deployment-1.2" xmlns:ejb="http://openejb.apache.org/xml/ns/openejb-jar-2.2" xmlns:log="http://geronimo.apache.org/xml/ns/loginconfig-2.0" xmlns:name="http://geronimo.apache.org/xml/ns/naming-1.2" xmlns:pers="http://java.sun.com/xml/ns/persistence" xmlns:pkgen="http://openejb.apache.org/xml/ns/pkgen-2.1" xmlns:sec="http://geronimo.apache.org/xml/ns/security-2.0" xmlns:web="http://geronimo.apache.org/xml/ns/j2ee/web-2.0.1">
<dep:environment>
<dep:moduleId>
<dep:groupId>DataStar</dep:groupId>
<dep:artifactId>DataStar</dep:artifactId>
<dep:version>1.0</dep:version>
<dep:type>car</dep:type>
</dep:moduleId>
<!--Don't load commons-io or fileupload from parent classloaders-->
<dep:hidden-classes>
<dep:filter>org.apache.commons.io</dep:filter>
<dep:filter>org.apache.commons.fileupload</dep:filter>
</dep:hidden-classes>
<dep:inverse-classloading/>
</dep:environment>
<web:context-root>/DataStar</web:context-root>
</web:web-app>
答案 7 :(得分:0)
这是一个使用apache commons-fileupload的例子:
// apache commons-fileupload to handle file upload
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(DataSources.TORRENTS_DIR()));
ServletFileUpload fileUpload = new ServletFileUpload(factory);
List<FileItem> items = fileUpload.parseRequest(req.raw());
FileItem item = items.stream()
.filter(e ->
"the_upload_name".equals(e.getFieldName()))
.findFirst().get();
String fileName = item.getName();
item.write(new File(dir, fileName));
log.info(fileName);
答案 8 :(得分:0)
您首先必须将表单的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();
//clocsing the input stream
}
}
}
}
答案 9 :(得分:-1)
你可以使用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 PRIVILEDGE*/
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();
}
}
}
}
答案 10 :(得分:-1)
DiskFileUpload upload=new DiskFileUpload();
从这个对象中你必须得到文件项和字段,然后你可以存储到服务器中,如下所示:
String loc="./webapps/prjct name/server folder/"+contentid+extension;
File uploadFile=new File(loc);
item.write(uploadFile);
答案 11 :(得分:-1)
最简单的方法是为文件和输入控件(没有十亿个库)提供一个
<%
if (request.getContentType()==null) return;
// for input type=text controls
String v_Text =
(new BufferedReader(new InputStreamReader(request.getPart("Text1").getInputStream()))).readLine();
// for input type=file controls
InputStream inStr = request.getPart("File1").getInputStream();
char charArray[] = new char[inStr.available()];
new InputStreamReader(inStr).read(charArray);
String contents = new String(charArray);
%>
答案 12 :(得分:-2)
发送文件的多个文件我们必须使用enctype="multipart/form-data"
并在输入标记
multiple="multiple"
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="fileattachments" multiple="multiple"/>
<input type="submit" />
</form>
答案 13 :(得分:-2)
HTML PAGE
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="UploadServlet" method="post"
enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
SERVLET FILE
// Import required java libraries
import java.io.*;
import java.util.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.output.*;
public class UploadServlet extends HttpServlet {
private boolean isMultipart;
private String filePath;
private int maxFileSize = 50 * 1024;
private int maxMemSize = 4 * 1024;
private File file ;
public void init( ){
// Get the file location where it would be stored.
filePath =
getServletContext().getInitParameter("file-upload");
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
// Check that we have a file upload request
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
if( !isMultipart ){
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("c:\\temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
out.println("Uploaded Filename: " + fileName + "<br>");
}
}
out.println("</body>");
out.println("</html>");
}catch(Exception ex) {
System.out.println(ex);
}
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
throw new ServletException("GET method used with " +
getClass( ).getName( )+": POST method required.");
}
}
的web.xml
编译上面的servlet UploadServlet并在web.xml文件中创建所需的条目,如下所示。
<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>