您好,我正在创建一个简单的java http套接字服务器,在其中我从客户端(浏览器)上载了一个文件,该文件将文件重新构造到了服务器中,但是问题是,在对带enctype的多份表单数据使用post方法时,编码会更改,这是我的代码
公共类服务器{
public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket(2929);
while (true) {
Socket client = server.accept();
InputStreamReader is = new InputStreamReader(client.getInputStream(),StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(is);
String line = "";
line = br.readLine();
System.out.println(line);
String temp = line,bound="";
int postDataI = 0;
while ((line = br.readLine()).length() != 0) {
System.out.println(line);
if (line.indexOf("Content-Length:") > -1) {
postDataI = new Integer(line.substring(line.indexOf("Content-Length:") + 16, line.length())).intValue();
}
if(line.indexOf("boundary") > -1){
bound = line.substring(line.indexOf("boundary") + 9);
}
}
System.out.println("bound = " + bound);
String fina="";
int count=0;
if(postDataI > 0){
br.readLine();
// to read the content
/*while(!(line = br.readLine()).contains(bound)){
System.out.println(line.length() + " " +line);
}*/
FileOutputStream os = new FileOutputStream(new File("filelocation/copy.jpg"));
int c = 0;
DataInputStream di = new DataInputStream(client.getInputStream()));
while((c = di.read())!= -1){
os.write(c);
System.out.print((char)c);
}
}
PrintWriter po = new PrintWriter(client.getOutputStream());
if (temp.length() == 14) {
po.print("HTTP/1.1 200\r\n");
po.print("Content-Type:text/html \r\n");
po.print("Connection:close \r\n");
po.print("\r\n");
po.print("<html>"
+ "<head><title>Upload</title></head>\n"
+ "<body>"
+ "<form accept-charset='UTF-8' ENCTYPE='multipart/form-data' method='POST' action='process.html'>"
+ "<input type='file' name='pic' accept='.jpg'>"
+ "<input type='submit' value='submit'>"
+ "</form>"
+ "</body>"
+ "</html>");
po.close();
} else if (temp.contains("process")) {
System.out.println("inside process");
po.print("HTTP/1.1 200\r\n");
po.print("Content-Type:text/html \r\n");
po.print("Connection:close \r\n");
po.print("\r\n");
po.print("processing");
po.close();
}
}
}
}
当我在控制台中读取输出时,文件的文本部分大部分是问号(?)。我上传了图片,并尝试对其进行重建。请帮助我提供不包含任何图像类的解决方案。我希望它是通用的,还是有其他方法可以在java http套接字服务器中上传