File Upload core point 1 (59), file upload core point 59
1: Use <input type = "file"/> to declare a file field. File: _____ <browse>.
2: You must use a post form.
3: You must set the form type to multipart/form-data. This is not the key = value passed by the form. The byte code is passed.
Example: how to obtain the content of an uploaded file (obtain a txt file)
PackageCn. hx. servlet;
ImportJava. io. BufferedReader;
ImportJava. io. IOException;
ImportJava. io. InputStream;
ImportJava. io. InputStreamReader;
ImportJava. io. PrintWriter;
ImportJavax. servlet. ServletException;
ImportJavax. servlet. http. HttpServlet;
ImportJavax. servlet. http. HttpServletRequest;
ImportJavax. servlet. http. HttpServletResponse;
/**
* If the type of a form is post and the enctype is multipart/form-date
* All data is transmitted to the server in binary mode.
* Therefore, req. getParameter ("xxx") is always null.
* You can only use req. getInputStream () to obtain data and body data.
*/
Public ClassUpServletExtendsHttpServlet {
Public VoidDoPost (HttpServletRequest req, HttpServletResponse resp)
ThrowsServletException, IOException {
Req. setCharacterEncoding ("UTF-8 ");
String txt = req. getParameter ("txt"); // The returned value is null.
System.Err. Println ("txt is:" + txt );
System.Err. Println ("========================================== ==== ");
InputStream in = req. getInputStream ();
// Byte [] B = new byte [1, 1024];
// Int len = 0;
// While (len = in. read (B ))! =-1 ){
// String s = new String (B, 0, len );
// System. err. print (s );
//}
BufferedReader br =NewBufferedReader (NewInputStreamReader (in ));
String firstLine = br. readLine (); // read the first line, and the first line is the separator number
String fileName = br. readLine ();
FileName = fileName. substring (fileName. lastIndexOf ("\") + 1); // bafasd.txt"
FileName = fileName. substring (0, fileName. length ()-1 );
Br. readLine ();
Br. readLine ();
String data =Null;
// Obtain the running path of the current project
String projectPath = getServletContext (). getRealPath ("/up ");
PrintWriter out =NewPrintWriter (projectPath + "/" + fileName );
While(Data = br. readLine ())! =Null){
If(Data. equals (firstLine + "--")){
Break;
}
Out. println (data );
}
Out. close ();
}
}