jsp通过二进制上传文件提示文件已损坏。
这是Jps书上的一个列子。。但是我照着打完之后。
上传的文件显示都损坏。但是只有TXT文本不损坏。EXCEL和WORD都显示损坏。这是为什么啊。
还有我没有什么servlet,因为我还没弄懂servlet是什么意思。。具体什么作用。
<%@ page contentType="text/html;charset=GBK"%>
<%@ page import="javax.servlet.*" %>
<%@ page import="javax.servlet.http.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<html><head><title>上传文件</title> </head>
<body>
<%
int MAX_SIZE = 102400*102400;
String rootPath;
DataInputStream in = null;
FileOutputStream fileOut = null;
String remoteAddr = request.getRemoteAddr();
String serverName = request.getServerName();
String realPath = request.getRealPath("/");
realPath = realPath.substring(0,realPath.lastIndexOf("\\"));
rootPath = realPath + "\\upload\\";
out.println("文件上传成功!");
String contentType = request.getContentType();
try{
if(contentType.indexOf("multipart/form-data")>=0){
in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
if(formDataLength > MAX_SIZE){
out.println("<P>上传的文件字节数不能超过"+MAX_SIZE+"</p>");
return;
}
byte dataBytes[]=new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while(totalBytesRead < formDataLength)
{
byteRead = in.read(dataBytes,totalBytesRead,formDataLength);
totalBytesRead +=byteRead;
}
String file = new String(dataBytes);
String saveFile= file.substring(file.indexOf("filename=\"")+10);
saveFile = saveFile.substring(0,saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\")+1,saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex+1,contentType.length());
String fileName = rootPath + saveFile;
int pos;
pos=file.indexOf("filename=\"");
pos=file.indexOf("\n",pos)+1;
pos=file.indexOf("\n",pos)+1;
pos=file.indexOf("\n",pos)+1;
int boundaryLocation = file.indexOf(boundary,pos)-4;
int startPos = ((file.substring(0,pos)).getBytes()).length;
int endPos = ((file.substring(0,boundaryLocation)).getBytes()).length;
File checkFile = new File(fileName);
if(checkFile.exists()){
out.println("<p>"+saveFile+"文件已存在</p>");
}
File fileDir= new File(rootPath);
if(!fileDir.exists()){
fileDir.mkdir();
}
fileOut = new FileOutputStream(fileName);
fileOut.write(dataBytes,startPos,(endPos-startPos));
fileOut.close();
out.println("<p.<font color=red size=5>"+saveFile+"文件上传成功!</font></p>");
}
else
{
String content = request.getContentType();
out.println("<p>上传的数据类型不是multipart/form-data</p>");
}
}catch(Exception ex)
{
throw new ServletException(ex.getMessage());
}
%>
</body>
</html>