<form name="articleform" class="form-horizontal" action="${pageContext.request.contextPath}/list" method="post" enctype="multipart/form-data"> <input type="text" name="id" /> <input type="file" name="image" size="100"
<input type="submit" value="提交" /> </form>
注意method必须为post,enctype必须为multipart/form-data。(具体原因可搜索下enctype几种属性的区别)
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); try { SmartUpload su=new SmartUpload(); //初始化SmartUpload ,必须有要,不然有异常 su.initialize(this.getServletConfig(),request,response); su.setMaxFileSize(1*1024*1024); su.setTotalMaxFileSize(10*1024*1024); su.setAllowedFilesList("jpg,png,JPG"); su.upload(); //获取其它参数 String id =su.getRequest.getParameter("id"); //获取文件,如果文件为多个,循环遍历即可 Files files=su.getFiles(); String fileName=files.getFile(0).getFileName(); //saveAs方法第二个参数用法可以自己详究一下 files.getFile(0).saveAs("/resources/images/article/"+fileName,File.SAVEAS_VIRTUAL); } }
代码只做示例作用,思路没有问题,但是代码是我截取的项目片段,也许存在一点小问题。
原文:https://www.cnblogs.com/nlw-blog/p/10890552.html