需要jar:commons-io-2.4.jar、commons-fileupload-1.3.1.jar
1.前端处理
<div id="uploadArea" style="display: none; text-align: center;">
<form id="uploadForm" action="<%=basePath%>/DemoServlet" method="post" enctype="multipart/form-data" name="fileForm">
浏览文件:<input id="fileArea" type="file" name="fileName">
<input type="button" onclick="fileSubmitCheck();" value="确定">
</form>
</div>
/**
* 文件上传前检查,是否已选择文件
*/
function fileSubmitCheck(){
var file = $("#fileArea").val();
if(file == "" || file == null){
alert("请选择文件");
}else{
fileForm.submit();
}
}
需要注意设置的编码类型为multipart/form-data,既文件上传类型
2.后台处理
/**
* 文件上传
* @param request
* @param response
*/
public void uploadFile(HttpServletRequest request, HttpServletResponse response){
String rstMsg = "上传成功";
ServletContext sc = getServletContext();
RequestDispatcher rd = null;
//获取文件保存路径,判断是否存在该目录如果不存在创建
Properties pr = new Properties();
InputStream is = this.getClass().getResourceAsStream("/uploadPath.properties");
try {
pr.load(is);
String savePath = pr.getProperty("recipes_save_file_path");//D\:\\recipe
File file = new File(savePath);
if(!file.exists() && !file.isDirectory()){
file.mkdirs();
}
//使用appche原生方式处理文件上传
DiskFileItemFactory factroy = new DiskFileItemFactory();
//创建文件上传解析器
ServletFileUpload upload = new ServletFileUpload(factroy);
//设置上传文件编码-文件名称乱码
upload.setHeaderEncoding("utf-8");
//3、判断提交上来的数据是否是上传表单的数据- 前端form表单要有enctype="multipart/form-data"属性
if(!ServletFileUpload.isMultipartContent(request)){
return;
}
//使用解析器解析上传的表单数据,每个FileItem对应一个表单项
List<FileItem> fileItemList = upload.parseRequest(request);
for(FileItem fileItem : fileItemList){
if(!fileItem.isFormField()){//不是普通的表单项,即是上传的是文件
//获取文件名称
String fileName = fileItem.getName();//不是getFieldName()方法
log.info("========fileName=====" + fileName);
if(fileName.isEmpty()){
return;
}
//截取文件名称,有些浏览器上传的是包括路径的文件名有些是只有文件名
fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
//获取上传文件输入流
InputStream in = fileItem.getInputStream();
//创建文件输出流
savePath += "\\" + fileName;
FileOutputStream out = new FileOutputStream(savePath);
//创建缓冲区
byte[] ary = new byte[1024];
//将数据读取到输出流中
int len = 0;
while((len = in.read(ary)) != -1){
out.write(ary, 0, len);
}
//删除处理文件上传时生成的临时文件
fileItem.delete();
//刷新此缓冲的输出流。这迫使所有缓冲的输出字节被写出到底层输出流中
//close 方法先调用其 flush 方法,然后调用其基础输出流的 close 方法
out.flush();
}else{
//2018年01月19日 处理非文件表单
System.out.println("表单中input name:" + fileItem.getFieldName() + ",对应的值:" + fileItem.getString("UTF-8"));
rstMap.put(fileItem.getFieldName(), fileItem.getString("UTF-8"));
}
}
} catch (Exception e) {
rstMsg = "上传失败";
log.info("===========文件上传失败===========" + e.getMessage());
e.printStackTrace();
}finally{
try {
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
=============================================================================
2018/12/04 add
新增上传文件另一方式
package cn.com.xu.servlet;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
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 C1700092 2018年12月4日 上午9:31:00
*
*/
public class UploadFileServlet extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{
//是否为文件上传,如果不是取消
if(!ServletFileUpload.isMultipartContent(req)){
resp.setContentType("text/html;charset=utf-8");
PrintWriter writer = resp.getWriter();
writer.println("不是文件上传");
writer.flush();
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
//创建文件上传解析实例
ServletFileUpload fileUpload = new ServletFileUpload(factory);
try {
List<FileItem> list = fileUpload.parseRequest(req);
if(list != null && list.size() > 0){
for(FileItem item : list){
if(item.isFormField()){
System.out.println("表单中input2 name:" + item.getFieldName() + ",对应的值:" + item.getString("UTF-8"));
}else{
//获取文件名称
String fileName = item.getName();
//创建上传文件保存路径
File file = new File("D:\\xyl\\webTest" + File.separator + fileName);
//上传
item.write(file);
resp.setContentType("text/html;charset=utf-8");
PrintWriter writer = resp.getWriter();
writer.println("上传成功");
writer.flush();
return;
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
详见:http://www.runoob.com/jsp/jsp-file-uploading.html