java 中如何向服务器上传图片
我们使用一些已有的组件帮助我们实现这种上传功能。
常用的上传组件:
Apache 的 Commons FileUpload
JavaZoom的UploadBean
jspSmartUpload
以下,以FileUpload为例讲解
1、在jsp端
<form id="form1" name="form1" method="post" action="servlet/fileServlet" enctype="multipart/form-data">
要注意enctype="multipart/form-data"
然后只需要放置一个file控件,并执行submit操作即可
<input name="file" type="file" size="20" >
<input type="submit" name="submit" value="提交" >
2、web端
核心代码如下:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
requestsetCharacterEncoding("UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = uploadparseRequest(request);
Iterator itr = itemsiterator();
while (itrhasNext()) {
FileItem item = (FileItem) itrnext();
if (itemisFormField()) {
Systemoutprintln("表单参数名:" + itemgetFieldName() + ",表单参数值:" + itemgetString("UTF-8"));
} else {
if (itemgetName() != null && !itemgetName()equals("")) {
Systemoutprintln("上传文件的大小:" + itemgetSize());
Systemoutprintln("上传文件的类型:" + itemgetContentType());
Systemoutprintln("上传文件的名称:" + itemgetName());
File tempFile = new File(itemgetName());
File file = new File(scgetRealPath("/") + savePath, tempFilegetName());
itemwrite(file);
requestsetAttribute("uploadmessage", "上传文件成功!");
}else{
requestsetAttribute("uploadmessage", "没有选择上传文件!");
}
}
}
}catch(FileUploadException e){
eprintStackTrace();
} catch (Exception e) {
eprintStackTrace();
requestsetAttribute("uploadmessage", "上传文件失败!");
}
requestgetRequestDispatcher("/uploadResultjsp")forward(request, response);
}
0条评论