常用的上传组件:
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 {
request.setCharacterEncoding("UTF-8")
DiskFileItemFactory factory = new DiskFileItemFactory()
ServletFileUpload upload = new ServletFileUpload(factory)
try {
List items = upload.parseRequest(request)
Iterator itr = items.iterator()
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next()
if (item.isFormField()) {
System.out.println("表单参数名:" + item.getFieldName() + ",表单参数值:" + item.getString("UTF-8"))
} else {
if (item.getName() != null &&!item.getName().equals("")) {
System.out.println("上传文件的大小:" + item.getSize())
System.out.println("上传文件的类型:" + item.getContentType())
System.out.println("上传文件的名称:" + item.getName())
File tempFile = new File(item.getName())
File file = new File(sc.getRealPath("/") + savePath, tempFile.getName())
item.write(file)
request.setAttribute("upload.message", "上传文件成功!")
}else{
request.setAttribute("upload.message", "没有选择上传文件!")
}
}
}
}catch(FileUploadException e){
e.printStackTrace()
} catch (Exception e) {
e.printStackTrace()
request.setAttribute("upload.message", "上传文件失败!")
}
request.getRequestDispatcher("/uploadResult.jsp").forward(request, response)
}
private File myFile //文件private String myFileContentType //类型
private String myFileFileName //文件名
//。。。。getXXX() setXXX()方法
//输入流
InputStream is = new FileInputStream(myFile)
//设定文件路径
String photoPath = ServletActionContext.getServletContext()
.getRealPath("/user/photo/")
File filePhotoPath = new File(photoPath)
//判断这个路径是否存在,如果不存在创建这个路径
if (!filePhotoPath.isDirectory()) {
filePhotoPath.mkdir()
}
String extension = FilenameUtils.getExtension(this
.getMyFileFileName()) //后缀名 比如jpg
String filename = UUID.randomUUID().toString() + "." + extension
// 目标文件
File tofile = new File(photoPath, filename)
// 输出流
OutputStream os = new FileOutputStream(tofile)
byte[] buffer = new byte[1024]
int length = 0
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length)
}
// 关闭输入流
is.close()
// 关闭输出流
os.close()
欢迎分享,转载请注明来源:夏雨云
评论列表(0条)