我的Servlet代码如下:
可以将数据保存到文件中,但是好像编码不符合,很急啊!!!package org.quasar.loader.uploader;import static java.lang.System.out;import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/*
 * @author Quasar
 * @version 0.1
 *  This servlet complete the function that allows a client to upload a file;
 *  The main idea is to analyse the inputstream and give the right response.
 */
public class UploadServlet extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse resp) {
doPost(req, resp);
}

public void doPost(HttpServletRequest req, HttpServletResponse resp) {
HttpSession session = req.getSession(true);
//define two state:Header represents no-operation;key represents a input type header; 
final int HEADER = 0;
final int KEY = 1;
//get all the data of form,and write them into br.
String sdata = getFormData(req);
out.println(sdata);
BufferedReader br = new BufferedReader(new StringReader(sdata));

//get Boundary and endBoundary
String contentType = req.getContentType();
String boundary = getBoundary(contentType);
String endBoundary = boundary + "--";
out.println("boundary:" + boundary);
//start analyze data
int state = HEADER;
String sline = new String();
try {
while((sline=br.readLine())  != null) {
switch(state) {
case HEADER:
if(sline.startsWith(boundary)) {
state = KEY;
}
break;
case KEY:
    int keyStart = sline.indexOf("name=") + new String("name=").length() + 1;
    out.println(keyStart);
    int keyEnd =  sline.indexOf(";", keyStart) - 1;
    out.println(keyEnd);
    String name = null;
    if(keyEnd < 0) {
     name = sline.substring(keyStart, sline.length()  - 1);
    } else {
     name = sline.substring(keyStart, keyEnd);
    }
   out.println("Key-Name:" + name);
   solveData(name.trim(), session, br, endBoundary);
   state = HEADER;
break;
    default:
out.println("KEY HEADER :update it!");
        break;
}
}
} catch (IOException e) {
out.println("Get data error at analyze stage!");
e.printStackTrace();
}
}

private String getFormData(HttpServletRequest req) {
String sdata = null;
try {
DataInputStream dis = new DataInputStream(req.getInputStream());
    int length = req.getContentLength();
    byte[] buffer = new byte[length];
    dis.readFully(buffer);
    sdata = new String(buffer);
} catch (IOException e) {
out.println("Can't get inputstream!");
e.printStackTrace();
}
return sdata;
}

private String getBoundary(String contenttype) {
String boundary = null;
int pos = contenttype.indexOf("boundary") + "boundary=".length();
int posend = contenttype.indexOf(";", pos) - 1;
boundary = "--" + contenttype.substring(pos) ;
return boundary;
}

private void solveData(String name, HttpSession session, BufferedReader br, String endBoundary ) {
if(name.equals("fileid") ) {
try {
while(br.readLine().equals("/r/n")) {
break;
}
String fileid = br.readLine().trim();
out.println("fieldid:" + fileid);
session.setAttribute("fileid", fileid);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if(name .equals("filetype") ) {
try {
while(br.readLine().equals("/r/n")) {
break;
}
String filetype = br.readLine().trim();
out.println("filetype:" + filetype);
session.setAttribute("filetype", filetype);

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if(name .equals("filedata") ) {
   String sin = null;
   DataOutputStream dos = null;
   File pic = new File("C:\\upload.jpg");
   try {
dos = new DataOutputStream(new FileOutputStream(pic));
} catch (FileNotFoundException e1) {
out.println("Into File Error!");
e1.printStackTrace();
}
try {
while(br.readLine().equals("/r/n")) {
break;
}
/*
   我猜是编码问题,保存为图片后,打不开!高手帮帮我!
   保存后,与上传的原图片文件大小不同,一个是1.57k另一个1.17K,怎么解决?
*/
while(!(sin = br.readLine()).startsWith(endBoundary)) {
//String bsin = new String(sin.getBytes(), "gbk");
byte[] buffer = sin.getBytes("utf-8");
dos.write(buffer);
dos.flush();
}
dos.flush();
dos.close();
out.println("OK!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
pic.createNewFile();
} catch (IOException e) {
out.println("Can't save!");
e.printStackTrace();
}
} else {
out.println("Update it!");
}
}
}

解决方案 »

  1.   

    jspSmartUpload推荐有这个~原来用过~感觉还不错~
      

  2.   

    你们的提醒是对的,谢谢,我是学生,我想了解学习一下Servlet的原理
      

  3.   

    这么多....
    图片是二进制内容,又不是字符。你的图片浏览器打不开肯定是你上传厚的的文件有问题了。至于图片解码,那是图片浏览器的事。你存的是二进制数据.而你说的:/*
             我猜是编码问题,保存为图片后,打不开!高手帮帮我!
             保存后,与上传的原图片文件大小不同,一个是1.57k另一个1.17K,怎么解决?
            */ 大小不一致,那就是你的io流处理有问题了....