Servlet 上传文件

package com.busymonkey;

import java.io.File;  
import java.io.FileInputStream;
import java.io.IOException;  
import java.io.OutputStream;
import java.net.URI;
import java.util.Iterator;  
import java.util.List;  
  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
import org.apache.commons.fileupload.FileItem;  
import org.apache.commons.fileupload.FileItemFactory;  
import org.apache.commons.fileupload.FileUploadException;  
import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
import org.apache.commons.fileupload.servlet.ServletFileUpload;  

import org.apache.hadoop.fs.*;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.IOUtils;
  
public class HadoopDownload extends HttpServlet {  
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  
        req.setCharacterEncoding("UTF-8");  
        fileControl(req, resp);  
    }  
  
    /**  
     * 上传文件的处理  
     */ 
    private void fileControl(HttpServletRequest req, HttpServletResponse resp) throws ServletException {  
  
        // 在解析请求之前先判断请求类型是否为文件上传类型  
        boolean isMultipart = ServletFileUpload.isMultipartContent(req);  
  
        // 文件上传处理工厂  
        FileItemFactory factory = new DiskFileItemFactory();  
  
        // 创建文件上传处理器  
        ServletFileUpload upload = new ServletFileUpload(factory);  
  
        // 开始解析请求信息  
        List items = null;  
        try {  
            items = upload.parseRequest(req);  
        }  
        catch (FileUploadException e) {  
            e.printStackTrace();  
        }  
  
        // 对所有请求信息进行判断  
        Iterator iter = items.iterator();  
        while (iter.hasNext()) {  
            FileItem item = (FileItem) iter.next();  
            // 信息为普通的格式  
            if (item.isFormField()) {  
                String fieldName = item.getFieldName();  
                String value = item.getString();  
//              String basePath = req.getRealPath("/home/hou/");         req.setAttribute(fieldName, value);  
            }  
            // 信息为文件格式  
            else {  
                String fileName = item.getName();  
                int index = fileName.lastIndexOf("\\");  
                fileName = fileName.substring(index + 1);  
                fileName = "123456.txt";
                req.setAttribute("realFileName", fileName);  
  
                // 将文件写入  
//                String path = req.getContextPath();  
//                String directory = "uploadFile";  
//                String basePath = "/home/hou/workspace/";   
//                String basePath = req.getRealPath("/home/hou/"); 
                String basePath = "/home/hou/workspace/";
                File file = new File(basePath, fileName);  
                try {  
                    item.write(file);  
                    String target = "hdfs://10.19.155.41:9000/newfile/123.txt";
                    FileInputStream fis = new FileInputStream(new File("/home/hou/workspace/123456.txt"));
                    Configuration config = new Configuration();
                    FileSystem fs = FileSystem.get(URI.create(target), config);
                    OutputStream os = fs.create(new Path(target));
                    IOUtils.copyBytes(fis, os, 4096, true);
                }  
                catch (Exception e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
  
//        try {  
//            req.getRequestDispatcher("/download").forward(req, resp);  
//        }  
//        catch (IOException e) {  
//            e.printStackTrace();  
//        }  
    }  
}


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
     <%  
 String path = request.getContextPath();  
 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
 %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 <html>  
   <head>  
     <base href="<%=basePath%>">  
       
     <title>文件上传</title>  
     <meta http-equiv="pragma" content="no-cache">  
     <meta http-equiv="cache-control" content="no-cache">  
     <meta http-equiv="expires" content="0">      
     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
     <meta http-equiv="description" content="This is my page">  
     <!--  
     <link rel="stylesheet" type="text/css" href="styles.css">  
     -->  
   </head>  
     
   <body>  
        <form action="download" method="post" enctype="multipart/form-data">  
            文件别名:<input type="text" name="filename"><br>  
            选择文件:<input type="file" name="fileupload"><br>  
            <input type="submit" value="提交">  
          
        </form>  
   </body>  
 </html>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>hadoop</groupId>
  <artifactId>hadoopDownload</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>hadoopDownload Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
     
    <dependency>    
        <groupId>javax.servlet</groupId>    
        <artifactId>servlet-api</artifactId>    
        <version>2.5</version>    
        <scope>provided</scope>    
    </dependency>
    
    <dependency>  
        <groupId>org.apache.hadoop</groupId>  
        <artifactId>hadoop-common</artifactId>  
        <version>2.6.0</version>  
    </dependency>  
    <dependency>  
        <groupId>org.apache.hadoop</groupId>  
        <artifactId>hadoop-hdfs</artifactId>  
        <version>2.6.0</version>  
    </dependency>  
    <!--  -->
    <dependency>  
        <groupId>jdk.tools</groupId>  
        <artifactId>jdk.tools</artifactId>  
        <version>1.7</version>  
        <scope>system</scope>  
        <systemPath>/home/hou/java/jdk1.7.0_79/lib/tools.jar</systemPath>  
    </dependency>
  </dependencies>
  <build>
    <finalName>hadoopDownload</finalName>
  </build>
</project>

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <javaee:display-name>Archetype Created Web Application</javaee:display-name>
  <servlet>
    <servlet-name>HadoopDownload</servlet-name>
    <servlet-class>com.busymonkey.HadoopDownload</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>HadoopDownload</servlet-name>
    <url-pattern>/download</url-pattern>
  </servlet-mapping>

</web-app>


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在JSP中使用Servlet来处理文件上传是一种常见的做法。以下是一个简单的示例代码: 1. 创建一个JSP页面(upload.jsp),用于显示文件上传表单: ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>文件上传</title> </head> <body> <h2>文件上传</h2> <form action="upload" method="post" enctype="multipart/form-data"> <input type="file" name="file" id="file"> <input type="submit" value="上传"> </form> </body> </html> ``` 2. 创建一个Servlet(UploadServlet),用于处理文件上传请求: ```java import java.io.File; import java.io.IOException; 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; @WebServlet("/upload") @MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB maxFileSize = 1024 * 1024 * 10, // 10MB maxRequestSize = 1024 * 1024 * 50) // 50MB public class UploadServlet extends HttpServlet { private static final String UPLOAD_DIR = "uploads"; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String applicationPath = request.getServletContext().getRealPath(""); String uploadPath = applicationPath + File.separator + UPLOAD_DIR; File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } Part filePart = request.getPart("file"); String fileName = getFileName(filePart); String filePath = uploadPath + File.separator + fileName; filePart.write(filePath); response.getWriter().println("文件上传成功"); } private String getFileName(Part part) { String contentDisposition = part.getHeader("content-disposition"); String[] elements = contentDisposition.split(";"); for (String element : elements) { if (element.trim().startsWith("filename")) { return element.substring(element.indexOf('=') + 1).trim().replace("\"", ""); } } return null; } } ``` 在上述代码中,使用了`@MultipartConfig`注解来指定文件上传相关的配置,包括文件大小阈值、最大文件大小和最大请求大小。在`doPost`方法中,通过`request.getPart("file")`获取文件的`Part`对象,然后使用`write`方法将文件保存到指定的路径。 3. 部署应用程序到支持Servlet的容器中(如Tomcat),然后访问upload.jsp页面即可看到文件上传表单。 这是一个简单的文件上传示例,你可以根据实际需求进行修改和扩展。同时,请确保在实际开发中处理上传文件时要进行适当的安全验证和错误处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值