网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

servlet3.0文件上传-创新互联

1.浏览器端:选择图片、提交表单,同时将图片发送给服务器




上传的内容,都在请求体中。
2.服务器端:
1)手动获得请求体,需要手动解析。request.getInputStream()
2)使用servlet3.0
3)第三方工具 – apache-commons-fileupload
4)struts2
servlet3.0文件上传

创新互联是一家专注网站建设、网络营销策划、小程序定制开发、电子商务建设、网络推广、移动互联开发、研究、服务为一体的技术型公司。公司成立十多年以来,已经为上千成都柴油发电机各业的企业公司提供互联网服务。现在,服务的上千客户与我们一路同行,见证我们的成长;未来,我们一起分享成功的喜悦。
@WebServlet("/FileUploadServlet")
@MultipartConfig        //表示支持文件上传,否则获得null

public class FileUploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
    //1 普通字段
    String username = request.getParameter("username");
    System.out.println(username);

    //2 上传字段
    Part part = request.getPart("image");
    //2.1 获得文件名   
    // * IE         --> C:\Users\liangtong\Desktop\heima.txt
    // * 其他浏览器  --> heima.txt
    String contentDisposition = part.getHeader("Content-Disposition");
    System.out.println(contentDisposition);
    // * 截取文件名
    int start = contentDisposition.indexOf("filename=") + 10;
    int end = contentDisposition.length() - 1;
    String fileName = contentDisposition.substring(start, end);

    // * 浏览器兼容  -- lastIndexOf() 如果没有获得返回 -1
    fileName = fileName.substring( fileName.lastIndexOf("\\") + 1);

    System.out.println(fileName);

    //2.2 获得上传文件内容
    InputStream is = part.getInputStream();

    //2.3 将流写入到服务器文件中
    // * 上传目录
    String dir = this.getServletContext().getRealPath("/WEB-INF/upload");
    File file = new File(dir , fileName);

    // * 流的对拷
    FileOutputStream out = new FileOutputStream(file);

    byte[] buf = new byte[1024];
    int len = -1;
   while( (len = is.read(buf)) != -1 ){
        out.write(buf, 0, len);
    }

    out.close();
    is.close();

}

protected void doPost(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
    doGet(request, response);
}

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


分享名称:servlet3.0文件上传-创新互联
本文网址:http://bjjierui.cn/article/dgspos.html

其他资讯