try {
String str = "0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for(int i = 0; i < 16; i++){
sb.append(str.charAt(random.nextInt(str.length())));
}
String goodsCode = sb.toString(); //以上为 测试时 随机生成的图片编号 实际应用时可以加上时间防止重复
FileItemFactory factory = new DiskFileItemFactory();
// 创建文件上传处理器
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
// 开始解析请求信息
List items = null;
items = upload.parseRequest(request);
// 对所有请求信息进行判断
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
// 信息为键值对参数的格式
if (item.isFormField()) {
String fieldName = item.getFieldName();
String value = item.getString("UTF-8"); //设置文本参数的读取格式
System.out.println(fieldName+"|"+value);
request.setAttribute(fieldName, value);
}
// 信息为图片的格式
else {
String fileName = item.getName();
int index = fileName.lastIndexOf("\\");
fileName = fileName.substring(index + 1);
request.setAttribute("realFileName", fileName);
String basePath = request.getSession().getServletContext().getRealPath("/img");
File file = new File(basePath, goodsCode+".jpg");
item.write(file);
}
request.setAttribute("msg","文件上传成功!");
}
request.getRequestDispatcher("/houtai/picture-add.jsp").forward(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
<form action="GoodsControl?method=addGoods" method="post" enctype="multipart/form-data" class="form form-horizontal" id="form-article-add">
<input type="text" class="input-text" value="" placeholder="" id="" name="goodsNum" >
<select class="select" name="goodsType">
<option>请选择</option>
<c:forEach items="${requestScope.fenleiList }" var="fenlei" >
<option value="${fenlei.fenleiId }">${fenlei.fenleiName }
</option>
</c:forEach>
</select>
<input type="text" class="input-text" value="" placeholder="" id="" name="goodsPrice" >
<textarea name="goodsContent" cols="" rows="" class="textarea" placeholder="说点什么...最少输入10个字符" datatype="*10-100" dragonfly="true" nullmsg="备注不能为空!" onKeyUp="textarealength(this,200)"></textarea>
<div class="clearfix cl">
<label class="form-label col-2">图片上传:</label>
<div class="formControls col-10">
<input type="file" value="" name="myfile">
</div>
</div>
<div class="clearfix cl">
<div class="Button_operation">
<button class="btn btn-primary radius" type="submit"><i class="icon-save "></i>保存并提交审核</button>
${requestScope.msg }
</div>
</div>
</form>