DBMNG数据库管理与应用

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

Servlet 3.0 文件上传示例(翻译)

Servlet 3.0 File Upload Example

服务端代码(Servlet):

package in.co.javatutorials;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

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;

/**
 * @author javatutorials.co.in
 */
@MultipartConfig          // indicates that request MIME type is multipart/form-data
@WebServlet("/upload")
public class FileUploadServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String responseMessage = "File Upload Successfull!!";

		// Get file part using HttpServletRequest抯 getPart() method
		Part filePart = request.getPart("file");
		// Extract file name from content-disposition header of file part
		String fileName = getFileName(filePart);
		String basePath = "C:" + File.separator + "temp" + File.separator;

		System.out.println("***** fileName: " + fileName);

		// Copy input file to destination path
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			File outputFilePath = new File(basePath + fileName);
			System.out.println("***** outputFilePath: " + outputFilePath.getAbsolutePath());			
			inputStream = filePart.getInputStream();
			outputStream = new FileOutputStream(outputFilePath);

			int read = 0;
			final byte[] bytes = new byte[1024];
			while ((read = inputStream.read(bytes)) != -1) {
				outputStream.write(bytes, 0, read);
			}

		} catch (FileNotFoundException fne) {
			fne.printStackTrace();
			responseMessage = "File Upload Failed!!";
		} finally {
			if (outputStream != null) {
				outputStream.close();
			}
			if (inputStream != null) {
				inputStream.close();
			}
		}

		// create and return response to client web browser
		response.setContentType("text/html;UTF-8");
		PrintWriter writer = response.getWriter();
		writer.write("<html>");
		writer.write("<head>");
		writer.write("<title>Servlet 3.0 File Upload Example </title>");
		writer.write("</head>");
		writer.write("<body>");
		writer.write("<h3>" + responseMessage + "</h3>");
		writer.write("</body>");
		writer.write("</html>");
		writer.close();
	}

	// Extract file name from content-disposition header of file part
	private String getFileName(Part part) {
		final String partHeader = part.getHeader("content-disposition");
		System.out.println("***** partHeader: " + partHeader);
		for (String content : part.getHeader("content-disposition").split(";")) {
			if (content.trim().startsWith("filename")) {
				return content.substring(content.indexOf('=') + 1).trim()
						.replace("\"", "");
			}
		}
		return null;
	}
}
客户端代码:


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Servlet 3.0 File Upload Example</title>
</head>
<body>
	<form method="post" action="/FileUploadExample/upload" enctype="multipart/form-data">  
		File<input type="file" name="file">
		<input type="submit" value="submit">
	</form>
</body>
</html>

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

豫公网安备 41010502002439号