html中file上传后保存到一个位置需要预先在服务端建一个保存目录。
举例如下:
1、创建上传form:
<form action="http://www.cs.tut.fi/cgi-bin/run/~jkorpela/echo.cgi"
enctype="multipart/form-data" method="post">
<p>
Type some text (if you like):<br>
<input type="text" name="textline" size="30">
</p>
<p>
Please specify a file, or a set of files:<br>
<input type="file" name="datafile" size="40">
</p>
<div>
<input type="submit" value="Send">
</div>
</form>
2、提交到后台服务端处理:
public void commonImgUpload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/xml charset=utf-8")
response.setCharacterEncoding("UTF-8")
PrintWriter pw = response.getWriter()
String xml = ""
String imgName = getParam(request, "imgName")
String imgValue = getParam(request, "imgValue")
String type = getParam(request, "type")
String encryptCode = getParam(request, "encryptCode")
log.debug("图片上传,图片名称:" + imgName + ",上传类型:" + type)
if (MD5Checker.check(encryptCode, imgName)) {
try {
String path = this.getClass().getClassLoader().getResource("").getPath()
log.info("当前路径:" + path)
path = path.replace("WEB-INF/classes/", "pictures/" + type + "/")
log.info("替换后路径:" + path)
File temp = new File(path)
if (!temp.isDirectory()) {
log.info("创建目录path: " + path)
temp.mkdirs()
}
path += imgName
log.info("图片全path: " + path)
FileUtil.saveFile(path, (new BASE64Decoder()).decodeBuffer(imgValue), "UTF-8")
xml = "success"
log.info("上传图片:" + path + "成功!")
} catch (Exception e) {
log.info("上传图片失败," + e.getMessage())
xml = "fail"
}
} else {
xml = "<data><resultCode>" + "09" + "</resultCode>" + "<resultMsg>" + "摘要验证错误" + "</resultMsg>" + "</data>"
}
pw.print(xml)
if (null != pw) {
pw.close()
}
}
3、保存路径:
WEB-INF/classes/pictures/111.jpg
html通过file获取文件路径方法:第一种: File f = new File(this.getClass().getResource("/").getPath())System.out.println(f)结果: C:\Documents%20and%20Settings\Administrator\workspace\projectName\bin 获取当前类的所在工程路径如果不加“/” File f = new File(this.getClass().getResource("").getPath())System.out.println(f)结果: C:\Documents%20and%20Settings\Administrator\workspace\projectName\bin\com\test 获取当前类的绝对路径; 第二种: File directory = new File("")//参数为空 String courseFile = directory.getCanonicalPath() System.out.println(courseFile)结果: C:\Documents and Settings\Administrator\workspace\projectName 获取当前类的所在工程路径第三种: URL xmlpath = this.getClass().getClassLoader().getResource("selected.txt")System.out.println(xmlpath)结果: file:/C:/Documents%20and%20Settings/Administrator/workspace/projectName/bin/selected.txt 获取当前工程src目录下selected.txt文件的路径htmlfile是html格式的文件,它其实是特殊的文本文件。它需要浏览器的解释,每种HTML标记符在使用中可带有不同的属性项,用于描述该标记符说明的内容显示不同的效果。html又称超文本标记语言,结构包括头部分(Head)、和主体部分(Body),其中头部(head)提供关于网页的信息,主体(body)部分提供网页的具体内容。