使用jsp上传文件
注:
此操作需要在tomcat的lib文件夹下引入Commons-io包
Apache Jar 包官方网址
下载Commons-io包
在项目中导入包:commons-fileupload
下载commons-fileupload包
另外需要在项目out.artifacts.web_war_exploded文件夹下新建文件夹(upload)
1.indexFile.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件上传</title>
</head>
<body>
<form action="doupload.jsp" method="post" enctype="multipart/form-data">
<p>姓名:<input type="text" name="user"></p>
<p>选择文件:<input type="file" name="nfile"></p>
<p><input type="submit" value="提交"></p>
</form>
</body>
</html>
2.doUpload.File
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload" %>
<%@ page import="org.apache.commons.fileupload.FileItemFactory" %>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory" %>
<%@ page import="java.util.List" %>
<%@ page import="org.apache.commons.fileupload.FileItem" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.io.File" %>
<%@ page import="org.apache.commons.fileupload.FileUploadException" %>
<%@ page import="java.util.Arrays" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>上传处理页面</title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
String uploadFileName= ""; //上传文件名
String fieldName = ""; //表单字段元素的name属性值
//表单中的enctype是否是multipart/form-data
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
//上传文件的存储路径,服务器文件系统上的绝对文件路径
String uploadFilePath = request.getSession().getServletContext().getRealPath("upload/");
if (isMultipart){
//有文件,解析表单中的所有文件
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
//设置最大限制
upload.setSizeMax(1024*300);
try {
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
if (item.isFormField()){
//普通表单
fieldName = item.getFieldName(); //获取name属性值
if (fieldName.equals("user")){
//输出表单字段的值 姓名
out.print(item.getString("utf-8")+"上传了文件.<br>");
}
}else{
//文件表单
//设置文件允许的类型
List<String> fileType = Arrays.asList("gif","bmp","png","jpg");
String fileName = item.getName(); // 文件名
if (fileName!=null && !fileName.equals("")){
//截取文件的后缀名
String ext = fileName.substring(fileName.lastIndexOf(".")+1);
if(!fileType.contains(ext)){
out.print("上传失败!文件类型只能是\"gif\",\"bmp\",\"png\",\"jpg\"");
}else{
File fullFile = new File(item.getName());
File saveFile = new File(uploadFilePath,fullFile.getName()); //保存文件
item.write(saveFile);
uploadFileName = fullFile.getName(); //上传文件名
out.print("上传成功后的文件是:"+uploadFileName);
}
}
}
}
}catch (FileUploadException e) {
out.print("上传失败,文件太大,全部文件的最大限制是:"+upload.getSizeMax()+"bytes!");
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}
%>
</body>
</html>