基于servlet3.0的文件上传

jsp页面关键代码

<body>
    <form action="uploadServlet" method="post" enctype="multipart/form-data">
  <input type="file" name="file">
  <input type="submit" value="提交">
  </form>
  </body>






处理上传文件的Servlet完整代码

package com.oraclewdp.action;



import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Enumeration;


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;




@MultipartConfig
@WebServlet(name="uploadServlet",urlPatterns="/uploadServlet")
public class uploadServlet extends HttpServlet {
@Override
public void init() throws ServletException {
super.init();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
String savePath=req.getServletContext().getRealPath("\\upload");
Collection<Part> parts=req.getParts();
if(parts.size()==1){
Part part=req.getPart("file");
String header=part.getHeader("Content-Disposition");
String fileName=getFileName(header);
part.write(savePath+"\\"+fileName);
}else{
for (Part part : parts) {
String header=part.getHeader("content-disposition");
String fileName=getFileName(header);
part.write(savePath+"\\"+fileName);
}
}
PrintWriter out=resp.getWriter();
out.println("上传成功");
out.flush();
}

public String getFileName(String header) {
String[] tempArr1=header.split(";");
String[] tempArr2=tempArr1[2].split("=");
String fileName=tempArr2[1].substring(tempArr2[1].lastIndexOf("\\")+1).replaceAll("\"", "");
return fileName;
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
super.service(req, resp);
}

@Override
public void destroy() {
super.destroy();
}

}
阅读更多
个人分类: web java基础
上一篇将Collection转转换成带分隔符的字符串的帮助类
下一篇多文件上传,使用js对文件进行校验,包括文件单个大小,格式,总的文件大小,文件是否为空等
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭