Servlet3.0上传图片示例

一、前端JSP页面

<%@page pageEncoding="UTF-8"%>




Servlet3.0实现文件上传


Servlet3.0实现文件上传




















用户名:
密码:
头像:




 

二、后台逻辑处理的Servlet,需要导入文件上传处理包:commons-io -2.4.jar、commons -fileupload -1.3.1.jar

package com.qubo.servlet3x;

import java.io.IOException;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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("/fileUpload1")
@MultipartConfig
public class FileUploadServlet1 extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* Servlet3.0中,没有提供直接获取上传文件的文件名方法。需要使用如下方式来获取文件名
*/
protected String getFileName(Part part) {
String fileName = null;
String cotentDesc = part.getHeader("Content-Disposition");
Pattern pattern = Pattern.compile("filename=\"(.+)\"");
Matcher matcher = pattern.matcher(cotentDesc);
if (matcher.find()) {
fileName = matcher.group(1);
}
return fileName;
}

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
String name = request.getParameter("username");
String password = request.getParameter("password");
Part part = request.getPart("photo");
String fileName = this.getFileName(part); //调用获取文件名的方法
String str = part.getName(); //前端jsp页面中指定的name属性的值,即中的photo
System.out.println("用户名:" + name + ",密码:" + password + ",文件名:" + fileName + ",图像输入框名:" + str);
String hzm = fileName.substring(fileName.indexOf("."));//获取文件的后缀名
part.write("E:/ZhuoXun JavaWeb/Servlet3.x/WebContent/img/" + new Date().getTime() + hzm);//文件的保存位置
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

你可能感兴趣的:(Servlet3.0上传图片示例)