JSP:<%@page contentType="text/html; charset=utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:set var="basePath" value="${pageContext.request.contextPath}" />
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>文件上传</title>
</head>
<body>
<form method="post" action="${basePath}/FileUploadServlet"
enctype="multipart/form-data">
测试字段1:
<input type="text" id="temp1" name="temp1" />
<br />
测试字段2:
<input type="text" id="temp2" name="temp2" />
<br />
选择文件:
<input type="file" id="file" name="file" />
<br />
测试字段3:
<input type="text" id="temp3" name="temp3" />
<br />
<input type="submit" value="上传" />
</form>
</body>
</html>
Servlet:
package chapter5.action;import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;public class FileUploadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
BufferedReader br = request.getReader();
String temp = null;
while ((temp = br.readLine()) != null) {
if (temp.indexOf("filename") > 1) {
// 取扩展名
String fileExtension = temp.substring(temp.indexOf('.'), temp
.length() - 1);
br.readLine();
br.readLine();
File file = new File(request.getSession().getServletContext()
.getRealPath("/")
+ System.currentTimeMillis() + fileExtension);
//输出流
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
String content = null;
while((content=br.readLine())!=null){
if(content.startsWith("-----------------------------")){
break;
}
byte[] b = content.getBytes();
for(int i=0; i<b.length; i++){
bos.write(b[i]);
}
//bos.write('\n');
}
bos.flush();
bos.close();
}
}
}
}
我的意思是用字符流读取JSP传过来的流,然后在流中,当读取到文件内容的时候,我就把字符串转换为byte[],然后再用字节流写入文件中,按道理应该是可以还原图片的,可是结果不行,请问有什么方法可以从流中把图片解析出来,并写到服务器中.

解决方案 »

  1.   

    思路是可以的。可能程序有bug吧,我猜测可能是while((content=br.readLine())!=null){
                        if(content.startsWith("-----------------------------")){
                            break;
                        }
                        byte[] b = content.getBytes();
                        for(int i=0; i<b.length; i++){
                            bos.write(b[i]);
                        }
                        //bos.write('\n');
                    }这段不能使用readline()读成字符再转byte,应该想办法直接读byte再仔细阅读下RFC2388吧,解析对就可以了。