当前位置: 代码迷 >> Java Web开发 >> jsp实现文件上传有关问题
  详细解决方案

jsp实现文件上传有关问题

热度:286   发布时间:2016-04-10 23:09:28.0
jsp实现文件上传问题

第一个文件uploadfile.jsp
<%@ page contentType="text/html;charset=GB2312" language="java" %>
<html>
<head><title>文件上传</title></head>
<body>
<form name="form1" method="post" action="acceptUploadFile.jsp" enctype="multlpart/form-data">
upload:
<label>
<input type="file" name="upfile" size="30"/>
</label>
<p>
<label>
<input type="submit" name="submit" value="提交" />
</label>
</p>
</form>
</body>
</html>

第二个文件 acceptUploadFile.jsp
<%@ page contentType="text/html;charset=GB2312" language="java" %>
<%@ 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");
   String path = request.getRealPath("/");
  
   File tempFile1 = new File(path,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();
   
    RandomAccessFile randomFile1 = new RandomAccessFile(tempFile1,"r");
    randomFile1.readLine(); //读取第一行数据
    String FilePath = randomFile1.readLine();
    int position = FilePath.lastIndexOf("\\"); //得到文件名
    //文件名中文处理
    String fileName = codeToString(FilePath.substring(position+1,FilePath.length()-1));
    randomFile1.seek(0); //重新定位指针到文件头
    long forthEnterPosition = 0;
    int forth = 1; //得到第四行回车符号的位置,这是上传文件的开始位置
    while((n = randomFile1.readByte()) != -1 && (forth <= 4)) {
    if( n == '\n') {
    forthEnterPosition = randomFile1.getFilePointer();
    forth++;
    }
    }
    //根据客户上传文件的名字,将该文件保存到磁盘中
    File FileUploadDir = new File(path,"upload");
    FileUploadDir.mkdir(); //生成上传文件的目录
    File saveFile1 = new File(path + "/upload", fileName);
    RandomAccessFile randomFile2 = new RandomAccessFile(saveFile1,"rw");
    randomFile1.seek(randomFile1.length());
    //找到上传的文件数据的结束位置,即倒数第四行
   long endPosition = randomFile1.getFilePointer();
   int j = 1;
   while((endPosition >= 0) && (j <= 4)) {
   endPosition--;
randomFile1.seek(endPosition);
if(randomFile1.readByte() == '\n') {
endPosition = randomFile1.getFilePointer();
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 />");
%>
  


为什么会报错啊~!求大神相告!

------解决方案--------------------
为什么会报错   这个问题不如        为什么报XXX错
  相关解决方案