jsp实现文件上传
文件上传
客户端提交表单,将文件传给服务器,就是文件上传.
表单标签 必须为 method="post"
enctype="multipart/form-data"
<h3>客户,请上传的头像</h3>
<form action="upload.jsp" method="post" enctype="multipart/form-data">
文件: <input type="file" name="userfile"><br><br>
<input type="submit" value="提交">
</form>
上传文件的基本要求:
上传文件的格式类型
上传文件的大小
上传文件的路径
上传文件的命名机制
java实现文件上传
1、jspsmartupload 文件上传组件 ,早些时间使用的多,简单
SmartUpload su = new SmartUpload();
su.initialize(pageContext);
su.upload();
//接表单值,如果有乱码,最好下载支持utf-8组件
out.print(su.getRequest().getParameter("username"));
String path = request.getServletContext().getRealPath("upload");
File f = new File(path);
if(!f.exists()){
f.mkdirs();
}
//上传文件
su.save(path);
//指定上传文件的目标路径 在服务器当前项目根目录下的upload目录
String path = request.getServletContext().getRealPath("upload");
File f = new File(path);
if(!f.exists()){
f.mkdirs();
}
//控制文件上传类型
su.setAllowedFilesList("jpg,png");
//控制上传文件的大小
su.setMaxFileSize(1024*100); 100KB
<%@ page import="com.jspsmart.upload.SmartUpload" %>
<%@ page import="java.io.File" %>
<%@ page import="com.jspsmart.upload.Files" %>
<%@ page import="java.util.UUID" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.util.Random" %>
<%@ page import="java.util.Date" %>
<%@ page contentType="text/html;charset=utf-8" language="java" %>
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<title>webrx-7031633</title>
</head>
<body>
<%
SmartUpload su = new SmartUpload();
su.initialize(pageContext);
su.setAllowedFilesList("jpg,png");
su.setMaxFileSize(1024*1024);
try {
su.upload();
//接表单值,如果有乱码,最好下载支持utf-8组件
out.print(su.getRequest().getParameter("username"));
//指定上传文件的目标路径 在服务器当前项目根目录下的upload目录
String path = request.getServletContext().getRealPath("upload");
File f = new File(path);
if (!f.exists()) {
f.mkdirs();
}
//上传文件
//su.save(path); 将文件全部指上传到指定目录下,文件使用原来名子,如果有重复覆盖
//从0开始
int c = su.getFiles().getCount();
//out.print(su.getFiles().getFile(0).getFileName());
Files fs = su.getFiles();
for(int n=0;n<c;n++){
com.jspsmart.upload.File fff = fs.getFile(n);
//String name = fff.getFileName();//原文件名
//使用uuid命名
String ext = fff.getFileExt();
//String name = UUID.randomUUID().toString()+"."+ext;
//使用年月日信息命名
//SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssS");
//Random r = new Random();
//int nn = r.nextInt(9999999);
//String name = sdf.format(new Date())+"_"+String.format("%07d",nn)+"."+ext;
//使用命名编号
String fname = fff.getFileName();
String basename = fname.substring(0,fname.lastIndexOf("."));
String name = path+"/"+fname;
File nf = new File(name);
int num = 0;
while(nf.exists()){
fname = basename+"("+ ++num + ")."+ext;
name = path+"/"+fname;
nf = new File(name);
}
fff.saveAs("./upload/"+fname,SmartUpload.SAVE_VIRTUAL);
//fff.saveAs("./upload/"+name,SmartUpload.SAVE_VIRTUAL);
}
}catch (Exception e){
out.print(e.getMessage());
}
%>
</body>
</html>
2、Commons FileUpload apache文件上传组件 目前使用是最多的
使用2个jar包文件
commons-fileupload-1.3.2.jar
commons-io-2.5.jar
@WebServlet("/UpFile.action")
public class UpFile extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//使用apache commons fileupload 上传
boolean isMultipart = ServletFileUpload.isMultipartContent(req);
String path = this.getServletContext().getRealPath("upload/");
//上传文件
if(isMultipart){
DiskFileItemFactory f = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(f);
try {
List<FileItem> items = upload.parseRequest(req);
for(FileItem ft : items){
if(ft.isFormField()){
//取得上传的表单字符串,
System.out.println(ft.getFieldName()+"="+ft.getString("utf-8"));
}else{
//如果没有选文件
//System.out.println(ft.getSize()); //0
//System.out.println(ft.getFieldName());//userfile 表单名
//System.out.println(ft.getName());//'' 空字符串
//System.out.println(ft.getContentType());//application/octet-stream
//97289
//userfile
//66ba2e6152f638cba76a99f77d0f74c31e86204c238d0-qIKBWz_fw658.jpg
//image/jpeg
//取得上传的文件名称
String filename = ft.getName();
//实现将文件写入到服务器指定的目录中
if(!"".equals(filename)) {
ft.write(new File(path, filename));
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(req);
String path = this.getServletContext().getRealPath("upload/");
if(isMultipart){
DiskFileItemFactory f = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(f);
try {
Map<String,List<FileItem>> maps = upload.parseParameterMap(req);
//直接接表单username 字符串值
String username = maps.get("username").get(0).getString("utf-8");
//直接接userface单文件
FileItem ft1 = maps.get("userface").get(0);
if(!ft1.getName().equals("")){
ft1.write(new File(path,ft1.getName()));
}
//直接接checkbox 多选表单
List<FileItem> itemss = maps.get("love");
for(FileItem ftc : itemss){
System.out.println(ftc.getString("utf-8"));
}
//直接接userfile 文件数目不定
List<FileItem> items = maps.get("userfile");
for(FileItem ft : items){
if(!ft.getName().equals("")){
ft.write(new File(path,ft.getName()));
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
3、cos 文件上传组件 性能最好, 最快, 是国外一家出版社编写的
4、sun在servlet3.0 时候 内置 直接实现文件上传
headers
content-disposition
content-type
upfile.jsp
<h3>servlet3 客户,请上传的头像</h3>
<form action="upload.action" method="post" enctype="multipart/form-data">
姓名:<input type="text" name="username"><br><br>
文件1: <input type="file" name="userfile1" multiple><br><br>
文件2: <input type="file" name="userfile2" ><br><br>
文件3: <input type="file" name="userfile3" ><br><br>
<input type="submit" value="提交">
</form>
upload.action
package com.fz.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
/**
* Created by webrx on 2017-05-06.
*/
@WebServlet("/upload.action") @MultipartConfig
public class Upload extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
//接表单值
String name = req.getParameter("username");
System.out.println(name);
//接单个文件文件
//Part uf = req.getPart("userfile");
//if(!uf.getSubmittedFileName().equals("")){
// uf.write(getServletContext().getRealPath("upload/")+uf.getSubmittedFileName());
//}
//接批量文件上传
Collection<Part> uf = req.getParts();
for(Part p : uf){
if(p.getHeader("content-type")==null) continue;
if(!p.getSubmittedFileName().equals("")){
p.write(getServletContext().getRealPath("upload/")+p.getSubmittedFileName());
}
}
//Part part = req.getPart("username");
/*
System.out.println(req.getParameter("username"));
Collection<Part> ps = req.getParts();
for(Part p : ps){
String name = p.getName();//表单名
//System.out.println(p.getHeader("content-disposition"));
//System.out.println(p.getHeader("content-type")); //如果为null 就是普通字符串表单
//System.out.println(p.getSubmittedFileName());
// p.getSubmittedFileName() 如果是null 则是普通表单
if(p.getHeader("content-type")==null){
//普通表单
}else{
//可能是文件,也可以是空文件
//form-data; name="userfile"; filename=""
//application/octet-stream
//实现文件上传到 c:/目录下
if(!p.getSubmittedFileName().equals("")) {
p.write("c:/"+p.getSubmittedFileName());
}
}
}
*/
}
}