import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
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;

/**
 * Servlet implementation class FileUploadServlet
 */
@WebServlet(name = "FileUploadServlet", urlPatterns = {"/upload"})
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void processRequest(HttpServletRequest request,
            HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        ServletContext servletContext = this.getServletContext();
        String realPath = servletContext.getRealPath("/upload");
        final Part filePart = request.getPart("file");
        final String fileName = getFileName(filePart);

        OutputStream out = null;
        InputStream filecontent = null;
        final PrintWriter writer = response.getWriter();

        try {
            System.out.println(realPath  + "@@@@@@@@@@@@@@@@@@@@@@@@@");
            System.out.println( File.separator +  "@@@@@@@@@@@@@@@@@@@@@@@@@");
            System.out.println( fileName + "@@@@@@@@@@@@@@@@@@@@@@@@@");
            out = new FileOutputStream(
                    new File(realPath + File.separator + fileName));
            filecontent = filePart.getInputStream();

            int read;
            final byte[] bytes = new byte[1024];

            while ((read=filecontent.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            writer.println("upload file " + fileName + " to path " + realPath);
        } catch (FileNotFoundException fne) {
            writer.println("no upload path or upload path is wrong.");
            writer.println("<br/> error: " + fne.getMessage());
        } finally {
            if (out !=null) {
                out.close();
            }
            if (filecontent != null){
                filecontent.close();
            }
            if (writer != null) {
                writer.close();
            }
        }
    }

    private String getFileName(final Part part) {
        // TODO Auto-generated method stub
        for (String content: part.getHeader("content-disposition").split(";")) {
            System.out.println(content + "####################");
            if (content.trim().startsWith("filename")) {
                String filename = content.substring(
                        content.lastIndexOf("\\") +  1).trim().replace("\"", "");
                System.out.println(filename + "####################");
                return "2.zip";

            }
        }
        return null;
    }

    /**
     * @see HttpServlet#HttpServlet()
     */
    public FileUploadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        processRequest(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        processRequest(request, response);
    }

}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>

<form method="POST" action="upload" enctype="multipart/form-data">
	choose a file:
	<input type="file" name=file id="file" /><br/><br/>
	<input type="submit" value="upload" name="upload" id="upload" />
</form>

</body>
</html>

  

JAVA SERVLET上传文件的样码的更多相关文章

  1. java servlet上传文件并把文件内容显示在网页中

    servlet3.0(JDK1.6)自带的API即可实现本地文件的上传,Servlet3.0新增了Part接口,HttpServletRequest的getPart()方法取得Part实现对象.下面我 ...

  2. JAVA servlet 上传文件(commons-fileupload, commons-io)

    <1>获取二进制文件流并输出 InputStream inputStream = request.getInputStream(); BufferedReader reader = new ...

  3. Servlet上传文件

    Servlet上传文件 1.准备工作 (1)利用FileUpload组件上传文件,须要到apache上下载commons-fileupload-1.3.1.jar 下载地址:http://common ...

  4. 原生Servlet 上传文件

    依赖jar <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons ...

  5. java 后台上传文件

    java 后台上传文件 public static String uploadFile(File file, String RequestURL) throws IOException { Strin ...

  6. 使用Servlet上传文件

    使用浏览器向服务器上传文件其本质是打开了一个长连接并通过TCP方式传输数据.而需要的动作是客户端在表单中使用file域,并指定该file域的name值,然后在form中设定enctype的值为mult ...

  7. Java ftp上传文件方法效率对比

    Java ftp上传文件方法效率对比 一.功能简介: txt文件采用ftp方式从windows传输到Linux系统: 二.ftp实现方法 (1)方法一:采用二进制流传输,设置缓冲区,速度快,50M的t ...

  8. Java+Selenium 上传文件,点击选择“浏览文件”按钮,报错invalid argument

    Java+Selenium 上传文件,点击选择"浏览文件"按钮,报错invalid argument 解决代码: Actions action=new Actions(driver ...

  9. servlet上传文件报错(三)

    1.具体报错如下 null null Exception in thread "http-apr-8686-exec-5" java.lang.OutOfMemoryError: ...

随机推荐

  1. textView代码设置文字居中失效 textView设置文字居中两种方法

    1.TextView的高度占据整个父控件的高度,然后设置TextView的Grayvity Center就可以了. 2.如果第一个方法不行,那么,textView的高度设置为warp_content, ...

  2. 用(bootstrap)Handsontable做表格,手动实现数据排序

    商品graph帐票时,用(bootstrap)Handsontable做表格,手动实现数据排序待解决的问题: 若使用控件本身的排序,必须指定colHead,colHead不能被copy,若想表头被co ...

  3. 如何使用malloc申请一个二位数组

    fscanf(file, "%d", &iVertexNum); // Read number of Vertices double **G = (double **)ma ...

  4. 程序员最值得听的歌曲TOP10

      No.10 一剪梅 费玉清 - 玉笛公子 <一剪梅>是1984年台湾同名电视剧的片头曲,原唱为林禹胜,经典版本由费玉清演唱,后又成为2009年霍建华.吕一主演电视剧<新一剪梅&g ...

  5. 导出csv用excel打开后数字不用科学计数法显示(0123456显示123456)

    从这儿抄过来的: http://zhejiangyinghui.iteye.com/blog/1149526 最近写了一个生成csv的程序,生成的csv其中有一列数字长度为13位,csv中查看没有问题 ...

  6. Python全栈 MySQL 数据库 (简述 、安装、基本命令)

    ParisGabriel              每天坚持手写  一天一篇  决定坚持几年 为了梦想为了信仰    开局一张图     一个月的python已经结束了  下面就是数据库了   先说M ...

  7. Python namedtuple(命名元组)使用实例

    Python namedtuple(命名元组)使用实例 #!/usr/bin/python3 import collections MyTupleClass = collections.namedtu ...

  8. 安卓自动化robotium工具简单使用(二)

    在学习安卓的这段时间里,刚好有个朋友有一个APP的应用需要开发. 我马上就动手开始做着试试,在完成开发的同时写了相应的自动化测试代码,使用的是robotium. 才接触安卓没几天,写的不太好,如果有好 ...

  9. 【bzoj2694】Lcm 莫比乌斯反演+线性筛

    题目描述 求$\sum\limits_{i=1}^n\sum\limits_{j=1}^m|\mu(gcd(i,j))|lcm(i,j)$,即$gcd(i,j)$不存在平方因子的$lcm(i,j)$之 ...

  10. 【bzoj2662】[BeiJing wc2012]冻结 分层图Spfa

    原文地址:http://www.cnblogs.com/GXZlegend 题目描述 “我要成为魔法少女!” “那么,以灵魂为代价,你希望得到什么?” “我要将有关魔法和奇迹的一切,封印于卡片之中„„ ...