首页 > Web开发 > 详细

Servlet3.0文件上传简单示例

时间:2015-10-28 15:52:28      阅读:348      评论:0      收藏:0      [点我收藏+]

Servlet:

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

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;

import org.apache.tomcat.util.http.fileupload.IOUtils;

@WebServlet(name = "FileUploadServlet", urlPatterns = {"/upload"})
@MultipartConfig
public class DynamicInvoke extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Part filePart = request.getPart("file");
		try(InputStream inputStream = filePart.getInputStream();){
			IOUtils.copy(inputStream, new FileOutputStream(String.format("D:/%s", request.getParameter("fileName"))));
		}
		response.getWriter().println("success");
	}

}


HTML:

<!DOCTYPE html>
<html>
    <head>
        <title>File Upload</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <form method="POST" action="upload" enctype="multipart/form-data" >
            File:
            <input type="file" name="file" id="file" /> <br/>
            FileName:
            <input type="text" value="temp.txt" name="fileName"/>
            <br>
            <input type="submit" value="Upload" name="upload" id="upload" />
        </form>
    </body>
</html>


Servlet3.0文件上传简单示例

原文:http://my.oschina.net/u/1756290/blog/523107

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!