【WebMail】利用commons.fileupload组件进行文件上传
程序员文章站
2022-07-13 22:45:40
...
利用commons.fileupload组件进行文件上传,首先要把下面的两个包导入web工程
Servlet:
import java.io.File;
import java.io.IOException;
import java.util.List;
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;
/**
* @author $KangMiao$
* 文件上传
*/
public class UploadServlet extends HttpServlet{
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
//获得一个文件上传对象
DiskFileItemFactory factory =
new DiskFileItemFactory();
ServletFileUpload sfu =
new ServletFileUpload(factory);
//获得所有request请求
List<FileItem> list = sfu.parseRequest(req);
for (FileItem item : list) {
if(item.isFormField()){ //判断参数是否为文件类型
System.out.println("非文件类型数据:"
+item.getFieldName()+"--"
+item.getName());
}else{
System.out.println("name:"+item.getName()); //获得上传文件路径
System.out.println("fileName:"+item.getFieldName());
System.out.println("contentType:"+item.getContentType()); //获得上传文件类型
System.out.println("size:"+item.getSize()); //上传文件大小
String fromPath = item.getName();
//获得保存文件的绝对路径
String savePath = this.getServletContext().
getRealPath("/")+"userfile";
File fromFile = new File(fromPath);
File toFile = new File(savePath,fromFile.getName());
item.write(toFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
JSP:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>文件上传</title>
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form action="upfile" method="post" enctype="multipart/form-data">
<input type="text" name="user">
文件上传:<input type="file" name="file1">
<input type="file" name="file2">
<input type="submit" value="上传">
</form>
<br>
<a href="downfile">文件列表</a>
</body>
</html>
上一篇: etcdctl的使用[v3版本]
推荐阅读
-
Spring Boot 利用WebUploader进行文件上传功能
-
利用SA FileUp组件进行多文件上传
-
使用commons-fileupload组件进行文件上传
-
模拟文件上传(三):使用apache fileupload组件进行文件批量上传
-
模拟文件上传(二):使用apache fileupload组件进行文件上传
-
模拟文件上传(三):使用apache fileupload组件进行文件批量上传
-
【WebMail】利用commons.fileupload组件进行文件上传
-
使用apache.commons.fileupload组件来进行文件上传
-
利用Blob进行文件上传的完整步骤
-
Spring Boot 利用WebUploader进行文件上传功能