首页 > Web开发 > 详细

文件上传(3.0 开始支持 3.0 以前需要第三方架包)

时间:2020-04-15 16:11:55      阅读:54      评论:0      收藏:0      [点我收藏+]
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 java.io.File;
import java.io.IOException;
import java.util.UUID;

@WebServlet(name = "UpLoadServlet" ,value="/upload")
@MultipartConfig //使用MultipartConfig注解标注改servlet能够接受文件上传的请求
public class UpLoadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
// 当添加了注解 是 原来怎么获得 就怎么获得
String studentName = request.getParameter("studentName");
// 获得 文件对象
Part part = request.getPart("studentPhoto");
// 获得文件名
String fileName = part.getSubmittedFileName();
// 截取后缀名
String ext = fileName.substring(fileName.indexOf("."));
// 获得新的文件名
String uuid = UUID.randomUUID().toString();
String newfileName = uuid+ext;
// 获得文件存放的地址
String path = this.getServletContext().getRealPath("/imgs");
// 判断文件夹 imgs 是否存在
File file =new File(path);
if (!(file.exists())){
file.mkdir();
}
// 得到保存的文件路径
String save_path = path +File.separator + newfileName;
part.write(save_path);

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

文件上传(3.0 开始支持 3.0 以前需要第三方架包)

原文:https://www.cnblogs.com/chenlong321/p/12706005.html

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