相信有过Web开发经历的小朋友,对于文件上传都不陌生,但如何在自己的网站上提供文件上传呢?我想一定难到过很多同学,我就是其中的一个,近段时间因为开发的需要,总结了一下Web端文件上传的原理,在这里和大家分享一下。
jsp页面的主要代码:
<body> <h1 id="单文件上传">单文件上传</h1> <hr/> <form action="upload" method="post" enctype="multipart/form-data"> 文件<input type="file" name="img1"/><br/> <input type="submit" value="上传"/> </form> <h1 id="文件重命名">文件重命名</h1> <hr/> <form action="upload2" method="post" enctype="multipart/form-data"> 文件名<input type="text" name="imgname"/><br/> 文件<input type="file" name="img1"/><br/> <input type="submit" value="上传"/> </form> <h1 id="自动生成文件名">自动生成文件名</h1> <hr/> <form action="upload3" method="post" enctype="multipart/form-data"> 文件<input type="file" name="img1"/><br/> <input type="submit" value="上传"/> </form> <h1 id="多文件上传">多文件上传</h1> <hr/> <form action="upload4" method="post" enctype="multipart/form-data"> 文件1<input type="file" name="img1"/><br/> 文件2<input type="file" name="img1"/><br/> 文件3<input type="file" name="img1"/><br/> <input type="submit" value="上传"/> </form> </body>
下面是具体的上传方法介绍
<strong>单文件上传:</strong>
SmartUpload smart = new SmartUpload(); smart.initialize(this.getServletConfig(),request,response); try { smart.upload(); smart.save("images"); } catch (SmartUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); }
文件重命名:
SmartUpload smart = new SmartUpload(); smart.initialize(this.getServletConfig(),request,response); try { smart.upload(); String imgname = smart.getRequest().getParameter("imgname"); String absPath = this.getServletContext().getRealPath("/images");//获取文件的保存路径 System.out.println(absPath); String ext = smart.getFiles().getFile(0).getFileExt();//获取文件的后缀名 String fileName = absPath+File.separator+imgname+"."+ext;//生成文件的保存名 System.out.println("File name="+fileName); smart.getFiles().getFile(0).saveAs(fileName); } catch (SmartUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); }
<strong>自动生成文件名:</strong>
SmartUpload smart = new SmartUpload(); smart.initialize(this.getServletConfig(),request,response); String disFile = ""; try { smart.upload(); //String imgname = smart.getRequest().getParameter("imgname"); IPTimeStamp ipts = new IPTimeStamp(); String imgname = ipts.getIPTimestamp(); String absPath = this.getServletContext().getRealPath("/images"); System.out.println(absPath); String ext = smart.getFiles().getFile(0).getFileExt(); String fileName = absPath+File.separator+imgname+"."+ext; System.out.println("File name="+fileName); smart.getFiles().getFile(0).saveAs(fileName); disFile = imgname+"."+ext; } catch (SmartUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); }
生成随机文件名的代码:
package cn.edu.hpu.util;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Random;public class IPTimeStamp { private String ip; public IPTimeStamp() { } public IPTimeStamp(String ip) { this.ip = ip; } public String getIPTimestamp() { StringBuffer buffer = new StringBuffer(); if(ip != null) { String [] digits = ip.split("\\."); for(String s : digits) { buffer.append(s); } } //时间 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String time = sdf.format(new Date()); buffer.append(time); Random random = new Random(); for(int i=0; i<4; i++) { buffer.append(random.nextInt(10)); } return buffer.toString(); } public static void main(String[] args) { IPTimeStamp ipts = new IPTimeStamp("192.168.19.121"); System.out.println(ipts.getIPTimestamp()); }}
<strong>多文件上传:</strong>
SmartUpload smart = new SmartUpload(); smart.initialize(this.getServletConfig(),request,response); try { smart.upload(); for(int i=0; i<smart.getFiles().getCount(); i++) { //String imgname = smart.getRequest().getParameter("imgname"); IPTimeStamp ipts = new IPTimeStamp(); String imgname = ipts.getIPTimestamp(); String absPath = this.getServletContext().getRealPath("/images");//文件保存的路径 String ext = smart.getFiles().getFile(i).getFileExt();//获得文件的后缀名 String fileName = absPath+File.separator+imgname+"."+ext;//生成上传文件的保存时的名字 System.out.println("File name="+fileName); smart.getFiles().getFile(i).saveAs(fileName); } } catch (SmartUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); }
相信看到这里,大家一定已经明白如何完成文件上传了。(如有错误还望指正。谢谢)

HTMLattributesarecrucialinwebdevelopmentforcontrollingbehavior,appearance,andfunctionality.Theyenhanceinteractivity,accessibility,andSEO.Forexample,thesrcattributeintagsimpactsSEO,whileonclickintagsaddsinteractivity.Touseattributeseffectively:1)Usese

The alt attribute is an important part of the tag in HTML and is used to provide alternative text for images. 1. When the image cannot be loaded, the text in the alt attribute will be displayed to improve the user experience. 2. Screen readers use the alt attribute to help visually impaired users understand the content of the picture. 3. Search engines index text in the alt attribute to improve the SEO ranking of web pages.

The roles of HTML, CSS and JavaScript in web development are: 1. HTML is used to build web page structure; 2. CSS is used to beautify the appearance of web pages; 3. JavaScript is used to achieve dynamic interaction. Through tags, styles and scripts, these three together build the core functions of modern web pages.

Setting the lang attributes of a tag is a key step in optimizing web accessibility and SEO. 1) Set the lang attribute in the tag, such as. 2) In multilingual content, set lang attributes for different language parts, such as. 3) Use language codes that comply with ISO639-1 standards, such as "en", "fr", "zh", etc. Correctly setting the lang attribute can improve the accessibility of web pages and search engine rankings.

HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

HTML is used to build websites with clear structure. 1) Use tags such as, and define the website structure. 2) Examples show the structure of blogs and e-commerce websites. 3) Avoid common mistakes such as incorrect label nesting. 4) Optimize performance by reducing HTTP requests and using semantic tags.

ToinsertanimageintoanHTMLpage,usethetagwithsrcandaltattributes.1)UsealttextforaccessibilityandSEO.2)Implementsrcsetforresponsiveimages.3)Applylazyloadingwithloading="lazy"tooptimizeperformance.4)OptimizeimagesusingtoolslikeImageOptimtoreduc


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
