DBMNG数据库管理与应用

书籍是全世界的营养品。生活里没有书籍,就好像没有阳光;智慧里没有书籍,就好像鸟儿没有翅膀。
当前位置:首页 > 经验分享 > Java开发

java之Servlet3.0文件上传示例

html页面代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>上传文件</title>
</head>
<body>
	<form action="upload" enctype="multipart/form-data" method="post">
		文件名:<input type="text" id="name" name="name"/><br/>
		选择文件:<input type="file" id="file" name="file"/><br/>
		<input type="submit" value="上传"/>
	</form>
</body>
</html>

java端代码:

package com.lee.upload;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@WebServlet(name="upload",urlPatterns="/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/html;charset=UTF-8");
		PrintWriter out=resp.getWriter();
		String filename=req.getParameter("name");
		Part part=req.getPart("file");
		out.println("上传的文件类型为"+part.getContentType()+"<br/>");
		out.println("上传的文件大小为:"+part.getSize());
		Collection<String> headerNames=part.getHeaderNames();
		for (String headname : headerNames) {
			out.println(headname+"--->"+part.getHeader(headname)+"<br/>");
		}
		File f=new File(getServletContext().getRealPath("/uploadFiles"));
		f.mkdir();
		part.write(getServletContext().getRealPath("/uploadFiles")+"/"+filename);
		
	}

	
}

本站文章内容,部分来自于互联网,若侵犯了您的权益,请致邮件chuanghui423#sohu.com(请将#换为@)联系,我们会尽快核实后删除。
Copyright © 2006-2023 DBMNG.COM All Rights Reserved. Powered by DEVSOARTECH            豫ICP备11002312号-2

豫公网安备 41010502002439号