web开发笔记——网页将指定格式文件上传至服务器

实现以下上传图片功能:
在这里插入图片描述
HTML页面:
form.html


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Logintitle>
head>
<body>
上传头像 <input type="submit" value="上传"/> form> body> html>

这里需要注意form的三个属性:

  • action代表表单需要提交的地址,这里提交到Servlet中所以填入Servlet的类名;
  • enctype代表表单内容的编码格式,要实现文件上传则需要填multipart/form-data;
  • 提交方式选择post。

接下来实现Servlet的处理代码,这里用Part getPart(String name)方法获取上传的文件(name为组件名),并将上传的文件类型限制为图片格式。
MyServlet.java

package Servlet;

import java.io.IOException;
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;

/**
 * Servlet implementation class MyServlet
 */
@WebServlet("/MyServlet")
//声明Servlet可以处理multipart/form-data格式的请求,location用来设置上传文件的存放路径,该路径必须存在否则会抛异常
@MultipartConfig(location="D:\\")
public class MyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MyServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		try {
			response.setContentType("text/html;charset=UTF-8");
			Part p = request.getPart("portrait");
			//判断是否为图片格式
			if(p.getContentType().contains("image")) {
				 String fname = getFileName(p);
				//用Part的write方法将其写入服务器
				p.write(fname);
				System.out.println(fname);
			}
			else response.getWriter().append("上传文件格式错误");
		}catch(Exception e) {
			System.out.println(e.toString());
		}finally {
			out.close();
		}
	}
	//获取上传文件的名称
	private String getFileName(Part part) {
		//上传文件的名称包含在Part实例名为content-disposition的Header里面
		String header = part.getHeader("Content-Disposition");
		//System.out.println(header);
		String fileName = header.substring(header.indexOf("filename=\""),header.lastIndexOf("\""));
		//System.out.println(fileName);
		fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
		return fileName;
	}	
}

运行HTML并选择“上传”,若上传的是图片格式的文件,该文件将会保存到MultipartConfig指定的位置中。

你可能感兴趣的:(web,java,html)