java文件上传

来源:互联网 发布:拓客宝软件怎么收费 编辑:程序博客网 时间:2024/05/21 16:28

表单应注意的地方:

<form name="form1" method="post" action="" enctype="multipart/form-data">.......</form>
后台中的方法1:

<span style="white-space:pre"></span>List<FileItem> fileItems = new ArrayList<FileItem>();Map<String, String> formFields = MultipartRequestParser.parse(request, fileItems, 10 * 1024 * 1024);String opId = formFields.get("opId");//表单中的数据不能通过request.getParameter()取得
String fileName = null;<span style="white-space:pre"></span>String pathM = "upload/operationLog/";<span style="white-space:pre"></span>AttachmentConfig cfg = new AttachmentConfig(pathM);<span style="white-space:pre"></span>AttachmentDao adao = SystemDaoFactory.createAttachmentDao();<span style="white-space:pre"></span>for (int i = 0; i < fileItems.size(); i++) { // 依次处理每个上传的文件<span style="white-space:pre"></span>FileItem item = (FileItem) fileItems.get(i);<span style="white-space:pre"></span>fileName = item.getName().substring(item.getName().lastIndexOf("\\") + 1);<span style="white-space:pre"></span>HibernateUtil.makePersistent(log);<span style="white-space:pre"></span>Attachment att = adao.createAttachment(cfg, fileName, ui, item.getInputStream(), <span style="white-space:pre"></span>OperationLog.class.getName(), log.getId().toString(),null);<span style="white-space:pre"></span>HibernateUtil.makePersistent(att);<span style="white-space:pre"></span>log.setPicName(att.getId().toString());//保存图片附件的ID<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/上面这个是自己定义的附件类 
后台中的方法2:
//保存附件<span style="white-space:pre"></span>String pathM = "upload/operationLog/";<span style="white-space:pre"></span>for (int i = 0; i < fileItems.size(); i++) { // 依次处理每个上传的文件<span style="white-space:pre"></span>FileItem item = (FileItem) fileItems.get(i);<span style="white-space:pre"></span>InputStream is = item.getInputStream();<span style="white-space:pre"></span>//图片存放路径+文件名+扩展名<span style="white-space:pre"></span>//String path = RouteUtil.getRequest().getSession().getServletContext().getRealPath("\\")+pathM+item.getName();<span style="white-space:pre"></span>String path = pathM+item.getName();<span style="white-space:pre"></span>log.setPicName(item.getName());//保存图片存放路径<span style="white-space:pre"></span>File file = new File(path);<span style="white-space:pre"></span>File dir  = file.getParentFile();<span style="white-space:pre"></span>if(!dir.exists()) <span style="white-space:pre"></span>{<span style="white-space:pre"></span>dir.mkdirs();<span style="white-space:pre"></span>}<span style="white-space:pre"></span>OutputStream os = new FileOutputStream(file);<span style="white-space:pre"></span>int size;<span style="white-space:pre"></span>byte[] buffer = new byte[4096];<span style="white-space:pre"></span>while ((size = is.read(buffer)) != -1) {<span style="white-space:pre"></span>os.write(buffer, 0, size);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>os.close();}

0 0
原创粉丝点击