最近在做一个公众号项目,设计到了文件上传等功能模块,特此记录,温故而知新。
Demo: 上传图片
第0步:环境配置,添加jar包 commons-fileupload-1.3.jar
第1步:
表单中添加 enctype=”multipart/form-data”
<form name="updateForm" id="updateForm" action="<%= request.getContextPath()%>/Commodity/InsertCommodityDo" method="post" enctype="multipart/form-data">
...
<p>
<label>原图(图片尺寸小于1M)</label>
<input type="file" name="image" id="image" class="field size1" />
</p>
...
第2步:
以插入商品为例:
protected void processRequestByFile(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
Commodity commodity = new Commodity();
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
try {
throw new Exception("Form enctype Error");
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints Threshold
factory.setSizeThreshold(512 * 1024);
ServletContext servletContext = this.getServletConfig()
.getServletContext();
File repository = (File) servletContext
.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(repository);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(10 * 1024 * 1024);
try {
// Parse the request
List<FileItem> items = upload.parseRequest(request);
// Process the uploaded items
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
// 判断为非文件字段的处理
if (item.isFormField()) {
String name = item.getFieldName();
String value = new String(item.getString().getBytes("iso-8859-1"), "UTF-8");//表单中的中文字段要转换格式
//String value = item.getString();
System.out.println("value ==" + value);
if (name.equals("commodityId")) {
commodity.setCommodityId(Integer.valueOf(value));
} else if (name.equals("commodityName")) {
commodity.setCommodityName(value);
} else if (name.equals("appendName")) {
commodity.setAppendName(value);
} else if (name.equals("price")) {
commodity.setPrice(Integer.valueOf(value));
}
...
//判断为“文件字段”的处理
else {
String fieldName = item.getFieldName();
String fileName = item.getName();
long sizeInBytes = item.getSize(); //
if ((fileName == null || "".equals(fileName))
|| sizeInBytes == 0) {
continue;
}
//将文件放到服务器端的特定路径下
String path = this.getServletConfig().getServletContext()
.getRealPath("/photo");
File uploadDir = new File(path);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
int index = fileName.lastIndexOf(File.separator);
if (index > 0) {
fileName = fileName.substring(index + 1,
fileName.length());
}
File fileToSave = new File(uploadDir, fileName);
// 获取输入流
try {
InputStream inputstream=item.getInputStream();
commodity.setPhoto(inputstream);//这种方式是将图片流存到DB中
item.write(fileToSave);//这种方法是利用fileupload组件中的方法直接写到服务器中的特定文件下
总结:代码很丑,越看越丑,而且这样上传文件的方式已经比较古老了,后期应该会更新用Spring MVC和Struts框架来上传文件的方式。