jsp实现文件上传

upload.jsp
<%@ page contentType="text/html; charset=UTF-8"%>
<html>
<head>
<title>upload</title>
</head>
<body bgcolor="#ffffff">

<form name="form1" METHOD="POST" ACTION="receive.jsp" ENCTYPE="multipart/form-data">请选择上传文件:
<INPUT TYPE="FILE" NAME="FILE1" SIZE="50" id="myfile">
<BR>
<INPUT TYPE="SUBMIT" VALUE="Upload">
</form>
</body>
</html>


receive.jsp

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ page import="java.net.*" %>
<%@ page import="java.io.*" %>
<html>
<head>
<title>
receieve
</title>
</head>
<body bgcolor="#ffffff">
<br>
<%
String tempFile = new String("mytempfile");
       File temp = new File("D:"+File.separator, tempFile);
       FileOutputStream o = new FileOutputStream(temp);
       InputStream fileSource = null;
       fileSource = request.getInputStream();

       byte[] b = new byte[8192];
       int n;

       while((n = fileSource.read(b)) != -1) {
         o.write(b, 0, n);
         o.flush();
       }
       fileSource.close();
       o.close();


       RandomAccessFile rf = new RandomAccessFile(temp, "r");
       rf.readLine();
       String FilePath = rf.readLine();
       int position = FilePath.lastIndexOf('//');
       String filename = new String(FilePath.substring(position+1,FilePath.length()-1).getBytes("ISO-8859-1"),

"UTF-8");
       rf.seek(0);
       long forthEnterPosition = 0;
       int forth = 1;
       while((n = rf.readByte()) != -1 && (forth <= 4)) {
         if(n == 10) {
           forthEnterPosition = rf.getFilePointer();
           forth++;
         }
       }
File FileUploadDir = new File("D:"+File.separator, "upload");
       FileUploadDir.mkdir();

       File savefile = new File("D:"+File.separator+"upload", filename);

       RandomAccessFile rf2 = new RandomAccessFile(savefile, "rw");


       rf.seek(rf.length());
       long endPosition = rf.getFilePointer();

       int j = 1;
       while((endPosition>=0) && (j<=2)) {
         endPosition--;
         rf.seek(endPosition);
         if(rf.readByte() == 10)
         j++;
       }

       rf.seek(forthEnterPosition);
       long startPoint = rf.getFilePointer();
       while(startPoint + 8192L <= endPosition-1) {
         n = rf.read(b);
         startPoint = rf.getFilePointer();
         rf2.write(b, 0, n);
       }

       while(startPoint < endPosition-1) {
         rf2.write(rf.readByte());
         startPoint = rf.getFilePointer();
       }


       rf2.close();
       rf.close();
       temp.delete();
       out.println("file: " + filename + " succeed to upload!");
%>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值