在servlet当中,经常用到文件上传,目前倒是有不少上传的组件,但我觉得还是自己动手试一下自己写一个比较好。于是就写了下面这些代码。
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DataInputStream in = null;
FileOutputStream out = null;
String contentType = null;
contentType = request.getContentType();
if (contentType != null
&& contentType.indexOf("multipart/form-data") != -1) {
String FileName = "C:\\myfile";
File file = new File(FileName);
out = new FileOutputStream(file);
in = new DataInputStream(request.getInputStream());
byte[] dataBytes = new byte[1024 * 2];
int byteRead = 0;
while ((byteRead = in.read(dataBytes)) != -1) {
out.write(dataBytes, 0, byteRead);
}
out.flush();
out.close();
}
}
<form id="form1" enctype="multipart/form-data" name="form1" method="post" action="servlet/FindSina">
<label>File
<input type="file" name="textfield"/>
</label>
<p>
<label>
<input type="submit" name="Submit" value="submit" />
</label>
</p>
</form>