标签:
jsp界面代码:
<body>
<form action="servlet/UploadServlet" enctype="multipart/form-data" method="post">
<table>
<tr>
<td>文件上传:</td>
<td>
<input type="file" name="file1">
</td>
</tr>
<tr>
<td>
<input type="submit" value="提交">
</td>
</tr>
</table>
</form>
</body>
后台代码:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
File file1 = null;
DiskFileUpload diskFileUpload = new DiskFileUpload();
try {
List<FileItem> list = diskFileUpload.parseRequest(request);
for(FileItem fileItem : list){
if(fileItem.isFormField()){
}
else{
File remoteFile = new File(new String(fileItem.getName().getBytes(),"UTF-8")); //服务器项目部署路径_E:\tomcat\tomcat\webapps\fileUploadDemo\attachment
file1 = new File(this.getServletContext().getRealPath("attachment"),remoteFile.getName());
file1.getParentFile().mkdirs();
file1.createNewFile();
InputStream inp = fileItem.getInputStream();
OutputStream oup = new FileOutputStream(file1);
byte[] buffer = new byte[1024];
int len = 0;
while((len = inp.read(buffer)) > -1){
oup.write(buffer); }
oup.close();
inp.close();
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
标签:
原文地址:http://www.cnblogs.com/gm007/p/5865215.html