JAVA SERVLET上传文件的样码

简介: import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.
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>

  

目录
相关文章
|
5月前
|
缓存 安全 Java
Java服务器端技术:Servlet与JSP的集成与扩展
Java服务器端技术:Servlet与JSP的集成与扩展
54 3
|
5月前
|
存储 缓存 前端开发
Servlet与JSP在Java Web应用中的性能调优策略
Servlet与JSP在Java Web应用中的性能调优策略
49 1
|
5月前
|
Java
Java使用FileInputStream&&FileOutputStream模拟客户端向服务器端上传文件(单线程)
Java使用FileInputStream&&FileOutputStream模拟客户端向服务器端上传文件(单线程)
100 1
|
5月前
Caused by: java.lang.ClassNotFoundException: javax.servlet.Filter
Caused by: java.lang.ClassNotFoundException: javax.servlet.Filter
83 3
|
5月前
|
存储 Java 关系型数据库
基于Servlet和JSP的Java Web应用开发指南
基于Servlet和JSP的Java Web应用开发指南
118 0
|
5月前
|
前端开发 安全 Java
在Java服务器端开发的浩瀚宇宙中,Servlet与JSP犹如两颗璀璨的明星,它们联袂登场,共同编织出动态网站的绚丽篇章。
在Java服务器端开发的浩瀚宇宙中,Servlet与JSP犹如两颗璀璨的明星,它们联袂登场,共同编织出动态网站的绚丽篇章。
35 0
|
5月前
|
Java 开发工具 Spring
【Azure Spring Cloud】使用azure-spring-boot-starter-storage来上传文件报错: java.net.UnknownHostException: xxxxxxxx.blob.core.windows.net: Name or service not known
【Azure Spring Cloud】使用azure-spring-boot-starter-storage来上传文件报错: java.net.UnknownHostException: xxxxxxxx.blob.core.windows.net: Name or service not known
|
6月前
|
安全 Java API
Java中的Servlet编程详解
Java中的Servlet编程详解
|
6月前
|
Java 数据库连接 开发者
Java中的Servlet生命周期详解
Java中的Servlet生命周期详解
|
6月前
|
安全 Java API
Java中的Servlet编程详解
Java中的Servlet编程详解