Servlet简单实现文件上传功能

来源:互联网 发布:淘宝做什么 编辑:程序博客网 时间:2024/05/18 03:01

使用简单的servlet实现文件的上传功能

package com.zhiwei.control;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.util.Date;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@WebServlet("/FileUpload")public class FileUpload extends HttpServlet {    private static final long serialVersionUID = 1L;    /*解决中文乱码问题:     * request.setCharacterEncoding("utf-8");     * response.setContentType("text/html;charset=utf-8");     */    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        request.setCharacterEncoding("utf-8");        InputStream is=request.getInputStream();        String fileName=request.getParameter("fileName");        String dirPath="d:/temp";        File dir = new File(dirPath);        if(!dir.exists()){            dir.mkdir();        }        if(request.getParameter("fileName")!=null){            System.err.println(request.getParameter("fileName"));        };        //文件路径        File file=new File(dirPath,new Date().getTime()+"");        if(!file.exists()){            file.createNewFile();        }        FileOutputStream fos=new FileOutputStream(file);        int length=0;        StringBuffer sb=new StringBuffer();        byte[] buf=new byte[1024];        while((length=is.read(buf))!=-1){            fos.write(buf, 0, length);            sb.append(new String(buf,0,length));        }        fos.close();        is.close();        response.setContentType("text/html;charset=utf-8");        response.getWriter().println(sb.toString()+"\n"+fileName);    }    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        doGet(request, response);    }}
0 0
原创粉丝点击