标签:
原创链接:http://www.cnblogs.com/yanqin/p/5345562.html
<form action="shangchuan.jsp" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="上传"> </form>
<%@page import="org.apache.struts2.json.JSONUtil"%> <%@page import="java.io.File"%> <%@page import="org.apache.commons.fileupload.FileItem"%> <%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%> <%@page import="org.apache.commons.fileupload.FileItemFactory"%> <%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%> <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); //设置上传文件大小 long maxSize = 10 * 1024 * 1024; upload.setSizeMax(maxSize); //拿到传过来的所有数据 List<FileItem> items = upload.parseRequest(request); List<Map<String,Object>> maps = new ArrayList<Map<String,Object>>(); //设置上传文件的路径 String path = request.getRealPath("resource/"+"123"); //遍历items for(FileItem item : items){ //判断是不是 普通表单元素 if(item.isFormField()){ /* 在form表单那里,将enctype设置成用二进制传输后,无法在用getPararmeter获得普通元素的值,要用如下方法。 //拿到 普通表单元素的名字 String name = item.getFieldName(); //判断是不是 我要的 表单元素 if(name.equals("username")){ String value = item.getString(); } */ }else{ //判断是不是真的上传文件了 if(item.getName()=="" || item.getSize() == 0){ return; }else{ //如果上传的目录不存在,就创建 File rootPath = new File(path); if(!rootPath.exists()){ rootPath.mkdirs(); } //获取上传文件的后缀 String fileName = item.getName(); String ext = getExt(fileName); long fileSize = item.getSize(); //生成文件名 String fname = UUID.randomUUID().toString()+ext; //上传文件 rootPath = new File(path,fname); item.write(rootPath); //返回这次上传的相关信息 String fpath = "resource/"+"123"; Map<String,Object> map = new HashMap<String,Object>(); map.put("name",fileName); map.put("size",fileSize); map.put("sizeString", fileSize+"字节"); map.put("url",fpath); maps.add(map); } } out.print(JSONUtil.serialize(maps)); } %> <%! //根据名字 得出后缀名 public String getExt(String name){ return name.substring(name.lastIndexOf("."), name.length()); } %>
标签:
原文地址:http://www.cnblogs.com/yanqin/p/5345562.html