文件上传-前后端(HTML+Servelt)
本文最后更新于 2024-11-02,文章内容可能已经过时。
1.引入包
实现文件上传需要使用到SmartUpload组件,需要引入对应jar包:
2.代码实现
前端
form标签必须加上 method="post" enctype="multipart/form-data" ,否则无法上传到servlet
<form id="booksAdd_form" method="post" enctype="multipart/form-data" action="${pageContext.request.contextPath}/books/BooksAddServlet">
<table class="table table-bordered text-center">
<tr>
<th style="vertical-align: middle;">书籍封面</th>
<td style="vertical-align: middle;">
<div class="input-group">
<input id="bookImg" type="file" class="form-control" name="bookImg" style="align:center">
</div>
</td>
</tr>
</table>
</form>
后端
- servlet层
public class BooksAddServlet extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//创建SmartUpload
SmartUpload su=new SmartUpload();
String filename=null;//文件名
//初始化对象,规定写法,无需理解
su.initialize(this.getServletConfig(), request, response);
//生成文件名,ip+当前时间戳+三位随机数(保证文件名唯一)
filename="/upload/"+new UploadDao().uploadPicture(su,request);
//将二进制内容转回正常的request
Request req=su.getRequest();
//将文件路径存入数据库
Books book=new Books();
book.setImg(filename);
int result=new BooksDao().addBooks(book);
request.getRequestDispatcher("BooksServlet").forward(request, response);
}
}
- service层
public class UploadService {
//定义服务器保存文件的路径
static final String filePath = "E:/Code/EclipseEEWorkspace/books_manager/WebContent/WEB-INF/upload/";
// 上传图书封面
public String uploadPicture(SmartUpload su, HttpServletRequest request) {
String filename = null;
try {
//上传准备
su.upload();
} catch (ServletException | IOException | SmartUploadException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//获取文件
Files fs = su.getFiles();
File f = fs.getFile(0);
//获取自定义的文件名称
filename = this.getUploadFilename(request, f);
try {
//另存为定义的路径
su.getFiles().getFile(0).saveAs(filePath + filename);
// su.save(filePath);
} catch (IOException | SmartUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return filename;
}
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 晨哥之家
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果
音乐天地