网页请求提交到另外一个jsp 进行处理

  • index.jsp
<%@ page language="java" import="java.util.*" 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">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'fileupload.jsp' starting page</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">
</head> <body>
<!-- enctype 默认是 application/x-www-form-urlencoded -->
<form action="AccepteUploadFile.jsp" enctype="multipart/form-data" method="post">
上传文件: <input
type="file" name="file1"><br /> <input type="submit"
value="提交" />
</form>
</body>
</html>
  • AccepteUploadFile.jsp
<%@ page contentType="text/html; charset=gb2312" language="java"
import="java.sql.*" errorPage=""%>
<%@ page import="java.io.*"%>
<%!public String codeToString(String str)
{
String s = str;
try
{
byte tempB[] = s.getBytes("ISO-8859-1");
s = new String(tempB);
return s;
}
catch (Exception e)
{
return s;
}
}%>
<%
String tempFileName = new String("tempFileName1");//接收上传的文件内容的临时文件的文件名
File tempFile1 = new File("f:/", tempFileName);
FileOutputStream outputFile1 = new FileOutputStream(tempFile1);
InputStream fileSource1 = request.getInputStream();//得到客户端提交的所有数据
byte b[] = new byte[1000];
int n;
while ((n = fileSource1.read(b)) != -1)
{
outputFile1.write(b, 0, n); //将得到的客户端数据写入临时文件
}
outputFile1.close();
fileSource1.close();
out.println("tempfile finish <br/>");
RandomAccessFile randomFile1 = new RandomAccessFile(tempFile1, "r"); String firstline = randomFile1.readLine();//读取第一行数据
out.println("firstline:" + firstline+"<br/>");
String FilePath = randomFile1.readLine();//读取第二行数据,这行数据包括了文件的路径和文件名
int position = FilePath.lastIndexOf('\\'); //文件名
String filename = codeToString(FilePath.substring(position + 1,
FilePath.length() - 1));
out.println("FilePath:" + FilePath+"<br/>");
randomFile1.seek(0);//重新定位指针到文件头
long forthEnterPosition = 0;
int forth = 1; //得到第4行回车符号的位置,这是上传文件的开始位置
while ((n = randomFile1.readByte()) != -1 && (forth <= 4))
if (n == '\n')
{
forthEnterPosition = randomFile1.getFilePointer();
forth++;
} File saveFile1 = new File("f:/", filename);
RandomAccessFile randomFile2 = new RandomAccessFile(saveFile1, "rw");
randomFile1.seek(randomFile1.length());
long endPosition = randomFile1.getFilePointer();//找到上传的文件数据的结束位置,即倒数第4行
int j = 1;
while ((endPosition >= 0) && (j <= 4))
{
endPosition--;
randomFile1.seek(endPosition);
if (randomFile1.readByte() == '\n')
j++;
}
randomFile1.seek(forthEnterPosition);
long startPoint = randomFile1.getFilePointer();
while (startPoint < endPosition - 1)
{
randomFile2.write(randomFile1.readByte());
startPoint = randomFile1.getFilePointer();
}
randomFile2.close();
randomFile1.close();
//tempFile1.delete();
out.print("file:" + filename + " succeed upload!<br/>");
response.getWriter().write("hello");
%>

网页请求提交到 servlet 进行处理

  • index.jsp
<%@ page language="java" import="java.util.*" 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">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'fileupload.jsp' starting page</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">
</head> <body>
<!-- enctype 默认是 application/x-www-form-urlencoded -->
<form action="servlet/fileServlet" enctype="multipart/form-data" method="post">
文件类型: <input type="text" name="filetype"><br />
上传文件: <input type="file" name="file1"><br /> <input type="submit" value="提交" />
</form> </body>
</html>
  • FileProgressServlet
  • package com;
    
    import java.io.*;
    import java.sql.Date;
    import java.text.SimpleDateFormat;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Random; import javax.servlet.ServletConfig;
    import javax.servlet.ServletContext;
    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.FileUploadException;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload; /*
    * servlet 保存上传文件
    */
    public class FileProgressServlet extends HttpServlet
    { private static final long serialVersionUID = -7744625344830285257L;
    private ServletContext sc;
    private String savePath; public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    {
    doPost(request, response);
    } public void init(ServletConfig config)
    {
    // 在web.xml中设置的一个初始化参数
    savePath = config.getInitParameter("savePath");
    sc = config.getServletContext();
    System.out.println("servler init");
    } public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    {
    request.setCharacterEncoding("UTF-8");
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    try
    {
    String type = "";
    String path = ""; List<FileItem> items = upload.parseRequest(request);
    Iterator<FileItem> itr = items.iterator();
    while (itr.hasNext())
    {
    FileItem item = (FileItem) itr.next();
    if (item.isFormField())
    {
    System.out.println("表单参数名:" + item.getFieldName()
    + ",表单参数值:" + item.getString("UTF-8"));
    type = item.getString("UTF-8");
    }
    else
    {
    path = getdir(type);
    if (path == "")
    {
    request.setAttribute("upload.message", "getpath error");
    }
    if (item.getName() != null && !item.getName().equals(""))
    {
    System.out.println("上传文件的大小:" + item.getSize());
    System.out.println("上传文件的类型:" + item.getContentType());
    System.out.println("上传文件的名称:" + item.getName()); File tempFile = new File(item.getName());
    Integer rdm = new Random().nextInt();
    File file = new File(path, getDataTimeString(true) +rdm.toString()+tempFile.getName().substring(tempFile.getName().indexOf('.')));
    item.write(file);
    System.out.println("保存的上传文件:" + file.getPath());
    request.setAttribute("upload.message", "上传文件成功!");
    }
    else
    {
    request.setAttribute("upload.message", "没有选择上传文件!");
    }
    }
    }
    }
    catch (FileUploadException e)
    {
    e.printStackTrace();
    System.out.println(e.getMessage());
    }
    catch (Exception e)
    {
    e.printStackTrace();
    System.out.println(e.getMessage());
    }
    request.getRequestDispatcher("/t2.jsp").forward(request, response);
    } private String getdir(String filetype)
    {
    if (filetype == null)
    {
    return "";
    }
    String path = "F:\\youme\\{0}\\" + getDataString() + "\\";
    switch (filetype)
    {
    case "":
    path = path.replace("{0}", "image");
    break;
    case "":
    path = path.replace("{0}", "vedio");
    break;
    default:
    return "";
    }
    try
    {
    java.io.File file = new java.io.File(path);
    if (!file.exists())
    {
    if (!file.mkdirs())
    {
    return "";
    }
    }
    return path;
    }
    catch (Exception ex)
    {
    return "";
    }
    finally
    { }
    } /*
    * 获取当前时间
    */
    private static String getDataTimeString(Boolean isfilename)
    {
    try
    {
    SimpleDateFormat formatter = null;
    if (!isfilename)
    {
    formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }
    else
    {
    formatter = new SimpleDateFormat("yyyyMMddHHmmss");
    }
    Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
    return formatter.format(curDate);
    }
    catch (Exception ex)
    {
    System.out.println(ex.getMessage());
    return "";
    }
    } /*
    * 获取当前日期
    */
    private static String getDataString()
    {
    try
    {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
    return formatter.format(curDate);
    }
    catch (Exception ex)
    {
    System.out.println(ex.getMessage());
    return "";
    }
    }
    }

    注意:这里用了组件commons-fileupload-1.3.jar进行文件操作

  • web.xml配置一下servlet(index.jsp提交路径)
    <servlet>
<description>This is the description </description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>FileProgressServlet</servlet-name>
<servlet-class>com.FileProgressServlet</servlet-class> <init-param>
<param-name>savePath</param-name>
<param-value>uploads</param-value>
</init-param>
</servlet> <servlet-mapping>
<servlet-name>FileProgressServlet</servlet-name>
<url-pattern>/servlet/fileServlet</url-pattern>
</servlet-mapping>

java 网页 保存上传文件的更多相关文章

  1. 《手把手教你》系列技巧篇(五十四)-java+ selenium自动化测试-上传文件-中篇(详细教程)

    1.简介 在实际工作中,我们进行web自动化的时候,文件上传是很常见的操作,例如上传用户头像,上传身份证信息等.所以宏哥打算按上传文件的分类对其进行一下讲解和分享. 2.为什么selenium没有提供 ...

  2. 《手把手教你》系列技巧篇(五十五)-java+ selenium自动化测试-上传文件-下篇(详细教程)

    1.简介 在实际工作中,我们进行web自动化的时候,文件上传是很常见的操作,例如上传用户头像,上传身份证信息等.所以宏哥打算按上传文件的分类对其进行一下讲解和分享. 2.为什么selenium没有提供 ...

  3. Java Servlet 接收上传文件

    在Java中使用 Servlet 来接收用户上传的文件,需要用到两个apache包,分别是 commons-fileupload 和 commons-io 包: 如果直接在doPost中,使用requ ...

  4. java使用ftp上传文件

    ftpServer是apache MINA项目的一个子项目,它实现了一个ftp服务器,与vsftpd是同类产品.Filezilla是一个可视化的ftp服务器. ftp客户端也有很多,如Filezill ...

  5. java使用httpcomponents 上传文件

    一.httpcomponents简介 httpcomponents 是apache下的用来负责创建和维护一个工具集的低水平Java组件集中在HTTP和相关协议的工程.我们可以用它在代码中直接发送htt ...

  6. 使用django表单,使网页添加上传文件,并分析文件。

    开发环境是: apache + python + django+ eclipse(开发环境) 欲达到目的: 在网页上,添加上传文件控件.然后读取csv文件,并分析csv文件. 操作步骤: django ...

  7. Java使用HttpURLConnection上传文件

    从普通Web页面上传文件非常easy.仅仅须要在form标签叫上enctype="multipart/form-data"就可以,剩余工作便都交给浏览器去完毕数据收集并发送Http ...

  8. Java模拟http上传文件请求(HttpURLConnection,HttpClient4.4,RestTemplate)

    先上代码: public void uploadToUrl(String fileId, String fileSetId, String formUrl) throws Throwable { St ...

  9. Java使用HttpClient上传文件

    Java可以使用HttpClient发送Http请求.上传文件等,非常的方便 Maven <dependency> <groupId>org.apache.httpcompon ...

随机推荐

  1. 返回泛型集合的SqlDBHelper

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using Entity; ...

  2. SDWebImage浅析

    第一部分 SDWebImage库的作用: 通过对UIImageView的类别扩展来实现异步加载替换图片的工作. 主要用到的对象: 1)UIImageView(WebCache)类别,入口封装,实现读取 ...

  3. iOS 11 Xcode9开发 新特性学习 (新方法篇)

    1 .  引入github (1) 在Xcode 9 中,引入了 gitHub,新源代码管理导航器 可以展示branch分支和 tag标签. (2)点进去,就可以看指定一次commit了哪些东西 2 ...

  4. Swift进阶 - 12个技巧

    听说你已经学习Swift几个月了,有没有想更进一步成为Swift高手的想法?我这里有11招秘技,各位施主且听我慢慢道来,结个善缘. 1. 扩展(Extension) 任务: 求数字的平方. // 菜鸟 ...

  5. 提高开发效率 -> 图片

    相比于文字, 我们从图片中获取的信息是更快和更多的. 所以, 应当大量使用图片, 大量地截图和看图, 不管是针对资料还是代码都应如此. 这里给大家推荐两个好用的小工具, 一个是截图(DuckLink ...

  6. jQuery仿Android锁屏图案应用

    在线演示 本地下载

  7. css transform常用变化解析

    本文旨在对常用变化做最直观的简析 translate 移动 translateX() X轴正方向移动(单位可为px,也可为%,为%时以自身为参照物) translateY() Y轴反方向移动 tran ...

  8. SDWebImage第三方库学习

    1.基本使用方法 //异步下载并缓存 - (void)sd_setImageWithURL:(nullable NSURL *)url NS_REFINED_FOR_SWIFT; //使用占位图片,当 ...

  9. 教你在windows10环境下如何安装minepy并成功运行!

    在学习使用sklearn做单机特征工程这篇文章时,发现在计算互信息时from minepy import MINE代码运行出错ModuleNotFoundError: No module named ...

  10. YII2笔记之二

    module id / module id /.../ controller id / action idmodule id / directory / controller id / action ...