单文件上传jsp/Servlet-创新互联

Servlet
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.IOException;

@WebServlet(name = "Servlet", urlPatterns = "/Servlet")
@MultipartConfig//单文件上传
public class Servlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String ufp = request.getSession().getServletContext().getRealPath("upload/");
        try {
            File file=new File(ufp);
            if (!file.exists()){
                file.mkdir();
            }
            Part part=request.getPart("ufile");
            String fileName=exf(part);
            part.write(ufp+File.separator+fileName);
            String message="上传文件名成功"+fileName;
            request.setAttribute("message",message);
            request.getRequestDispatcher("show.jsp")
                    .forward(request,response);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private String exf(Part part) {
        String a=part.getHeader("content-disposition");
        String [] items=a.split(";");
        for (String s:items){
           if (s.trim().startsWith("filename")){
                return s.substring(s.indexOf("=")+2,s.length()-1);
            }
        }
        return "";
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
    }
}
jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>$Title$
上传文件:

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧

成都创新互联于2013年创立,先为华宁等服务建站,华宁等地企业,进行企业商务咨询服务。为华宁企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。
当前文章:单文件上传jsp/Servlet-创新互联
链接URL:http://ybzwz.com/article/cdiedj.html