


How to use HTML to upload images on the page and share the sample code for display
html页面:
本功能实现图片上传并显示,点击“查看”按钮也显示图片
<p class="form-group"> <label class="col-md-2 control-label">缩略图</label> <p class="col-md-2"> <input type="hidden" name="news.thumbnail_atta_id" value="${news.thumbnail_atta_id!}" id="thumbnail_atta_id"/> <p class="col-md-2"> @ if (!isEmpty(news.thumbnail_atta_id)) { <p class="row" style="margin-bottom:5px;"> <button type="button" class="btn btn-primary" id="showThumbnail">查看</button> </p> @ } <p class="row"> <span class="btn btn-success fileinput-button"> <i class="glyphicon glyphicon-plus"></i> <span>上传...</span> <input id="fileupload" type="file" data-url="/atta/upload/news-thumbnail" multiple> </span> </p> </p> <p> <img src="/static/imghwm/default1.png" data-src="" id=" class="lazy" id="thumbnail" style="max-width:90%" style="max-width:90%" style="display:none;"/ alt="How to use HTML to upload images on the page and share the sample code for display" > </p> </p> </p>
js代码:
<script type="text/JavaScript"> //缩略图文件上传 $('#fileupload').fileupload({ dataType: 'json', add: function(e, data) { var acceptFileTypes = /(\.|\/)(gif|jpe?g|png)$/i; if(data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) { alert('请上传图片格式的文件!') } else { data.submit(); } }, done: function (e, data) { $('#thumbnail_atta_id').val(data.result.id); $('#thumbnail').attr('src', data.result.url).show(); } }); //查看缩略图 $('#showThumbnail').click(function(){ var src = $('#thumbnail').attr('src'); var id=$('#thumbnail_atta_id').val(); if (!src) { $.get('/atta/show/${news.thumbnail_atta_id!}', function(res) { var url=localurl+res[0].url; //var url = "www.baidu.com/img/bd_logo1.png"; alert(url); $('#thumbnail').attr('src', url).show(); }, 'json') } }) </script>
Java代码:
Controller类:
/** * 上传并返回附件ID及URL */ public void upload() { UploadFile file = getFile(); String fileName = file.getFileName(); String fileSuffix = getSuffix(fileName); String module = getPara(0); String category = getPara(1); String id = AttachmentService.me.uploadFile(file, module, category); Map<String, Object> json = new HashMap<String, Object>(); json.put("id", id); json.put("url", "/upload/" + category + "/" + module + "/" + id + fileSuffix); json.put("name", fileName); renderJson(json); } /** * 返回给定ID的附件的访问URL */ public void show() { String ids = getPara(); if (null == ids) { ids = getPara("ids"); } String[] idArr = ids.split(","); StringBuffer sql = new StringBuffer(); sql.append(" select * from attachment where id in ( "); for (int index = 0; index < idArr.length; index++) { sql.append(" ? "); if (index != idArr.length - 1) { sql.append(" , "); } } sql.append(" ) "); List<Map<String, Object>> json = new ArrayList<Map<String,Object>>(); List<Attachment> list = Attachment.me.find(sql.toString(), (Object[])idArr); //转换成JsonArray String url = null; for (Attachment atta : list) { url = getAttaURL(atta); Map<String, Object> item = new HashMap<String, Object>(); item.put("id", atta.getStr("id")); item.put("url", url); item.put("name", atta.getStr("name")); json.add(item); } renderJson(json); } private String getAttaURL(Attachment atta) { StringBuffer path = new StringBuffer(); path.append(File.separator + "upload" + File.separator); path.append(atta.getStr("category")); path.append(File.separator); path.append(atta.getStr("module")); path.append(File.separator); path.append(atta.getStr("id")); path.append(getSuffix(atta.getStr("name"))); return path.toString(); } private String getSuffix(String name) { return name.replaceAll(".*(\\..*)", "$1"); }
service类:
/** * 上传文件 * @param file uploadFile * @param module 模块,如news/cases/doctor/ * @param category 分类,如缩略图thumbnail/头像avatar/幻灯片ppt * @return 附件主键 * @throws IOException */ public String uploadFile(UploadFile file, String module, String category) { String attachmentId = CommonUtils.getUUID(); File f = file.getFile(); new Attachment().set("id", attachmentId) .set("name", file.getOriginalFileName()) .set("size", f.length()) .set("content_type", file.getContentType()) .set("module", module) .set("category", category) .set("upload_time", new Date()) .save(); try { //重命名 String dirPath = file.getSaveDirectory(); File renamedFile = new File(dirPath + attachmentId + file.getOriginalFileName().replaceAll(".*(\\..*)", "$1")); FileUtils.moveFile(f, renamedFile); //PPT需要转换成图片,拷贝一份到转换目录(/upload/trans/ppt) if (category.equals("ppt")) { FileUtils.copyFileToDirectory(renamedFile, new File(dirPath + "trans/ppt/"), true); } //拷贝到对应的目录下 FileUtils.moveToDirectory(renamedFile, new File(dirPath + category + File.separator + module), true); } catch(Exception e) { e.printStackTrace(); } return attachmentId; }
The above is the detailed content of How to use HTML to upload images on the page and share the sample code for display. For more information, please follow other related articles on the PHP Chinese website!

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

The role of HTML is to define the structure and content of a web page through tags and attributes. 1. HTML organizes content through tags such as , making it easy to read and understand. 2. Use semantic tags such as, etc. to enhance accessibility and SEO. 3. Optimizing HTML code can improve web page loading speed and user experience.

HTMLisaspecifictypeofcodefocusedonstructuringwebcontent,while"code"broadlyincludeslanguageslikeJavaScriptandPythonforfunctionality.1)HTMLdefineswebpagestructureusingtags.2)"Code"encompassesawiderrangeoflanguagesforlogicandinteract

HTML, CSS and JavaScript are the three pillars of web development. 1. HTML defines the web page structure and uses tags such as, etc. 2. CSS controls the web page style, using selectors and attributes such as color, font-size, etc. 3. JavaScript realizes dynamic effects and interaction, through event monitoring and DOM operations.

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

HTML is suitable for beginners because it is simple and easy to learn and can quickly see results. 1) The learning curve of HTML is smooth and easy to get started. 2) Just master the basic tags to start creating web pages. 3) High flexibility and can be used in combination with CSS and JavaScript. 4) Rich learning resources and modern tools support the learning process.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6
Visual web development tools