jsp通过二进制上传文件提示文件已损坏。

q172282851 2014-12-28 05:09:09
这是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>
...全文
264 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
GrayHJX 2017-02-15
  • 打赏
  • 举报
回复
建议是用第三方的包来实现文件上传,对于excel,doc之类的文件单单二进制流可能不够用
乔不思 2014-12-30
  • 打赏
  • 举报
回复
书上的上传文件也写的太费劲了吧,你先用javase写一个复制文件的例子,然后把复制的 目的路径改为 上传的那个路径 就OK了,页面的话,无非就是添加一个标签,选择文件,其实都一样

81,092

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧