众所周和,java在做web项目开发时,经常用到文件上传功能,如果上传在这里插入代码片用户头像,照片,上传word文件等。这时候 可以用jspSmartUpload组件实现文件上传下载功能。
使用前必须注意一下几点:
```css
<%--如果表单里有文件类型,提交时一定要加上enctype="multipart/form-data" --%>
<form action="/MonkeyShopping/manage/admin_doproductadd" method="post" enctype="multipart/form-data" id="myform" name="myform">
<table class="insert-tab" width="100%">
<tbody>
<tr>
<th><i class="require-red">*</i>图书名称:</th>
<td>
<input class="common-text required" id="title" name="productName" size="50" value="" type="text">
</td>
</tr>
<tr>
<th><i class="require-red">*</i>图书图片:</th>
<td>
<input class="common-text required" id="title" name="productPhoto" size="50" value="" type="file">
<%--因为上传的是图片,即文件,所以type="file"--%>
</td>
</tr
<tr>
<th></th>
<td>
<input class="btn btn-primary btn6 mr10" value="提交" type="submit">
<input class="btn btn6" onClick="history.go(-1)" value="返回" type="button">
</td>
</tr>
</tbody></table>
</form>
**
JspSmartUpload的使用方法:**1.首先下载jar包,导入到web -> WEB_INF -> lib文件中。jspSmartUpload.jar(已解决utf-8乱码问题)
2.然后,使用的大致代码如下:
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
* 因为我们在productadd.jsp文件中的表单提交的<form>标签中写了 enctype="multipart/form-data"
* 所以无法通过 request.getParameter(String s); ——>获取界面的参数
* */
//创建SmartUpload对象
//SmartUpload su = new SmartUpload();
SmartUpload su = new SmartUpload();
//初始化
su.initialize(this.getServletConfig(),request,response);
//上传过程
try {
su.upload();
} catch (SmartUploadException e) {
e.printStackTrace();
}
//获取上传的文件对象
Files fs = su.getFiles();
File f = fs.getFile(0);
String fname = f.getFileName(); //获取文件名
try {
f.saveAs("/images/product",1);
su.save("img/product");
} catch (SmartUploadException e) {
e.printStackTrace();
}
// System.out.println(fname);
Request req1 = su.getRequest();
String pname = req1.getParameter("productName");
// String pname = new String(pname1.getBytes("GBK"),"utf-8");
String id = req1.getParameter("productId");
String price = req1.getParameter("productPrice");
String desc = req1.getParameter("productDesc");
String stock = req1.getParameter("productStock");
System.out.println("doproductAdd:"+pname); //这个可以暂时解决中文乱码问题
MONKEY_PRODUCT p = new MONKEY_PRODUCT(0,
pname,
desc,
Integer.parseInt(price),
Integer.parseInt(stock),
Integer.parseInt(id.split("-")[0]),
Integer.parseInt(id.split("-")[1]),
fname);
int count = MONKEY_PRODUCTDao.insert(p);
if(count > 0){
response.sendRedirect("admin_productselect");
}else {
PrintWriter out = response.getWriter();
out.write("<script>");
out.write("alert('图书添加失败');");
out.write("location.href='admin_toproductadd';");
out.write("</script>");
}
}
其他需要补充的参考这篇博客:https://blog.csdn.net/qq_35890572/article/details/79928182