servlet的上传文件

1.servlet部分

public class usephotoServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Usephoto up = new Usephoto();
try {
//文件的上传
//创建上传文件的对象
SmartUpload smart = new SmartUpload();
//初始化该对象
smart.initialize(this.getServletConfig(), request, response);
//设置允许上传的文件的后缀
smart.setAllowedFilesList("jpg");
//设置不能上传的文件的类型
smart.setDeniedFilesList("exe");
//设置单个文件允许上传的大小
smart.setMaxFileSize(1024*1024*10);
//设置总共允许上传的总共大小
smart.setTotalMaxFileSize(1024*1024*15);

//准备上传
smart.upload();

//通过smartupload对象获取request对象
Request r = smart.getRequest();
String upName = null;
String uid = r.getParameter("uid");
//获取表单中所有的file类型 的控件,返回一个Files
Files filelist= smart.getFiles();

//获取项目的路径
String path= this.getServletContext().getRealPath("\\")+"Upload\\";
//遍历控件
//filelist.getCount():获取当前控件的个数
for(int i=0;i<filelist.getCount();i++){
//filelist.getFile(i):获取当前的控件
File file = filelist.getFile(i);
//判断当前控件是否被选中
//isMissing():是否被选中,选中返回false,没有选中返回true
if(!file.isMissing()){
//获取该文件的文件名称
String name=file.getFileName();
//获取随机名
name =GetFileName.getFileName(name);
upName=name;
//保存文件
file.saveAs(path+name);
}
}
up.setUid(uid);
up.setUpName(upName);
} catch (SQLException e) {
e.printStackTrace();
} catch (SmartUploadException e) {
e.printStackTrace();
}
usephotoDaoImp udaoimp = new usephotoDaoImp();
udaoimp.addUsePhoto(up);
List<Usephoto> uplist  =udaoimp.seleUsePhoto(up.getUid(),6, 1);
HttpSession session = request.getSession();
session.setAttribute("uplist", uplist);
response.sendRedirect("oneTimeBoby/myPhoto.jsp");
}

}

2.jsp部分

<form action="usephotoServlet" method="post"  enctype="multipart/form-data" >
<table>
<tr><td colspan="2"><input type="hidden" name="uid" value="${sessionScope.u.uid }"/></td></tr>
<tr>
<td><input type="file" name="uImg"/><input type="text" name="tphoto"/></td><td><input type="submit" value="确认上传"/></td></tr>
</table>
</form>

3.jar包

jspsmartupload.jar

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在JSP中使用Servlet来处理文件是一种常见的做法。以下是一个简单的示例代码: 1. 创建一个JSP页面(upload.jsp),用于显示文件表单: ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>文件</title> </head> <body> <h2>文件</h2> <form action="upload" method="post" enctype="multipart/form-data"> <input type="file" name="file" id="file"> <input type="submit" value="上"> </form> </body> </html> ``` 2. 创建一个Servlet(UploadServlet),用于处理文件请求: ```java import java.io.File; import java.io.IOException; 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("/upload") @MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB maxFileSize = 1024 * 1024 * 10, // 10MB maxRequestSize = 1024 * 1024 * 50) // 50MB public class UploadServlet extends HttpServlet { private static final String UPLOAD_DIR = "uploads"; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String applicationPath = request.getServletContext().getRealPath(""); String uploadPath = applicationPath + File.separator + UPLOAD_DIR; File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } Part filePart = request.getPart("file"); String fileName = getFileName(filePart); String filePath = uploadPath + File.separator + fileName; filePart.write(filePath); response.getWriter().println("文件成功"); } private String getFileName(Part part) { String contentDisposition = part.getHeader("content-disposition"); String[] elements = contentDisposition.split(";"); for (String element : elements) { if (element.trim().startsWith("filename")) { return element.substring(element.indexOf('=') + 1).trim().replace("\"", ""); } } return null; } } ``` 在上述代码中,使用了`@MultipartConfig`注解来指定文件相关的配置,包括文件大小阈值、最大文件大小和最大请求大小。在`doPost`方法中,通过`request.getPart("file")`获取文件的`Part`对象,然后使用`write`方法将文件保存到指定的路径。 3. 部署应用程序到支持Servlet的容器中(如Tomcat),然后访问upload.jsp页面即可看到文件表单。 这是一个简单的文件示例,你可以根据实际需求进行修改和扩展。同时,请确保在实际开发中处理上文件时要进行适当的安全验证和错误处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值