日期:2014-05-16 浏览次数:20526 次
<html> <head> <title>文件上传</title> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> </head> <body> <b>文件上传</b></font></p> <form name="UploadForm" enctype="multipart/form-data" method="post" action="Xs.jsp"> <input type="file" name="File1" size="20" maxlength="20"> <br> <input type="submit"value="上传"> </form> </body> </html>?
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%@page import="java.io.*"%>
<%@page import="java.sql.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'Xs.jsp' starting page</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"/>
<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>
<%!
//此方法用于将指定的文本转换成ISO-8859-1字符编码格式
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");
//在D盘建立一个临时文件,名为tempFileName
File tempFile1 = new File("D:/", tempFileName);
//根据指定的这个临时文件,来创建一个文件字节输出流(用于向磁盘写文件)
FileOutputStream outputFile1 = new FileOutputStream(tempFile1);
//由返回一个文件字节输入流(用于读文件)
InputStream fileSource1 = request.getInputStream();
//实例一个字节数组初始为1000kb
byte b[] = new byte[1000];
int n;
//利用while循环,先读出这个文件大小,判断为不为-1,如果不为-1就输出数据,向磁盘写文件数据
while ((n = fileSource1.read(b)) != -1) {
outputFile1.write(b, 0, n); //将 n 个字节从b字节数组写入到outputFile1文件,偏移量从0开始
}
//关闭文件输出流
outputFile1.close();
//关闭文件输入流
fileSource1.close();
//实例化一个RandomAccessFile 对象.创建从中读取和向其中写入(可选)的随机存取文件流,该文件由 File 参数指定。
//将创建一个新的 FileDescriptor 对象来表示此文件的连接。
//mode 参数指定用以打开文件的访问模式。允许的值及其含意为:
//"r" 以只读方式打开。调用结果对象的任何 write 方法都将导致抛出 IOException。
//"rw" 打开以便读取和写入。如果该文件尚不存在,则尝试创建该文件。
//"rws" 打开以便读取和写入,对于 "rw",还要求对文件的内容或元数据的每个更新都同步写入到基础存储设备。
//"rwd" 打开以便读取和写入,对于 "rw",还要求对文件内容的每个更新都同步写入到基础存储设备。
RandomAccessFile randomFile1 = new RandomAccessFile(tempFile1, "r");
//读取文本的下一行
randomFile1.readLine();
//读取文本的下一行返回一个String
String FilePath = randomFile1.readLine();
//对页面首次加载进行处理
if(FilePath == null)
{
FilePath = "";
}else
{
//得到最后一次出现\\符号的索引位置
int position = FilePath.lastIndexOf('\\');
//将截取到的文本(position + 1, FilePath.length() - 1)转换成ISO-8859-1格式的字符串(得到文件的名字)
String filename = codeToString(FilePath.substring(position + 1, FilePath.length() - 1));