JSP上传文件到指定位置实例代码
/** 直接取上传的File */
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String targetPath = request.getRealPath(request.getContextPath()); // 目标存储路径,服务器部署目录下
request.setCharacterEncoding("UTF-8");
try {
DefaultFileItemFactory factory = new DefaultFileItemFactory();
DiskFileUpload up = new DiskFileUpload(factory);
List<FileItem> ls = up.parseRequest(request);
for (FileItem file : ls) {
if (file.isFormField()) { // 判断是文件还是文本信息
System.out.println("表单参数名:" + file.getFieldName()+ ",表单参数值:" + file.getString("UTF-8"));
} else {
if (file.getName() != null && !file.getName().equals("")) { // 判断是否选择了文件
File sFile = new File(file.getName());// 构造临时对象,此时文件暂存在服务器的内存当中
File tFile = new File(targetPath, sFile.getName());
if(tFile.exists()){
System.out.println("同名文件已上传!");
}else{
//FileUtils.copyFileToDirectory(sFile, tFile);//直接复制并上传到服务器,自动生成上机目录,目录名称与上传文件的名称一致
FileUtils.copyFile(sFile, tFile); // 直接复制并上传文件到服务器,直接在指定位置生成目标文件
System.out.println("文件上传成功");
if (tFile.isDirectory()) { // 删除上传文件
FileUtils.deleteDirectory(tFile);
} else if (tFile.isFile()) {
tFile.delete();
}
System.out.println("文件删除成功");
}
} else {
System.out.println("没有选择上传文件!");
}
}
}
} catch (FileUploadException e) {
System.out.println("文件上传失败!");
e.printStackTrace();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>test.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/servlet/MyServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
<body>
<form method="post" action="servlet/MyServlet" encType="multipart/form-data" >
<font color="blue">可直接发布zip文件</font> <br />
发布流程文件 :<input type="file" name="processDef" />
<input type="submit" value="部署"/>
</form>
</body>