package service.file;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FileUploadServlet extends HttpServlet {
static final int LENGTH = 256;
/**
*
*/
private static final long serialVersionUID = 1623087173696875199L;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
uploadFile(request, response);
}
public void uploadFile(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
ServletInputStream sis = request.getInputStream();
String filePath = "D:/file.abc";
String boundary = getBoundary(request);
FileOutputStream fos = new FileOutputStream(filePath);
byte[] buf = new byte[LENGTH];
byte[] next = new byte[LENGTH];
int len = 0;
int length = 0;
while (true) {
len = sis.readLine(buf, 0, buf.length);
//System.out.println(new String(buf, 0, len));
if (byteIndexOf(buf, "Content-Type:", 0) != -1) {
break;
}
}
len = sis.read(buf, 0, bytesLen("/r/n"));
int i = 0;
length = sis.readLine(next, 0, next.length);
System.out.println(new String(next, 0, length) + "-----1");
len = length;
while (len != -1) {
buf = null;
buf = new byte[LENGTH];
System.arraycopy(next,0,buf,0,len);
length = sis.readLine(next, 0, next.length);
if (byteIndexOf(next, boundary, 0) != -1) {
if (buf.length > 2) {
fos.write(buf, 0, len - 2);
//fos.write(buf, 0, len);
i++;
System.out.println("find-----" + i);
}
System.out.println(new String(next) + "-----2");
break;
}
i++;
fos.write(buf, 0, len);
len = length;
//len = sis.read(buf, 0, buf.length);
}
fos.close();
sis.close();
}
public String getBoundary(HttpServletRequest request) {
String contentType = request.getContentType();
int start = contentType.indexOf("boundary=");
int boundaryLen = new String("boundary=").length();
String boundary = contentType.substring(start + boundaryLen);
boundary="--"+boundary;
return boundary;
}
private int byteIndexOf (byte[] source,String search,int start)
{
return byteIndexOf(source,search.getBytes(),start);
}
private int byteIndexOf (byte[] source,byte[] search,int start)
{
int i;
if (search.length==0)
{
return 0;
}
int max=source.length-search.length;
if (max<0)
return -1;
if (start>max)
return -1;
if (start<0)
start=0;
// 在source中找到search的第一个元素
searchForFirst:
for (i=start;i<=max ; i++)
{
if (source[i]==search[0])
{
//找到了search中的第一个元素后,比较剩余的部分是否相等
int k=1;
while(k<search.length)
{
if (source[k+i]!=search[k])
{
continue searchForFirst;
}
k++;
}
return i;
}
}
return -1;
}
private static int bytesLen(String s)
{
return s.getBytes().length;
}
}