关闭

基于servlet3.0的文件上传

标签: webservlet文件上传Servlet3.0新特性
132人阅读 评论(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();
}

}
1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1896次
    • 积分:101
    • 等级:
    • 排名:千里之外
    • 原创:8篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档