ajaxfileupload上传图片抱java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
使用springmvc以及spring的标签,jquery1.7.1
尝试过在表单添加enctype="multipart/form-data",但这样在提交表单时就传不了参数页面表单<form:form id="inputForm" modelAttribute="clazz" action="${ctx}/sys/clazz/save" method="post">
<input type="hidden" name="id" value="${clazz.id}"/>
<fieldset class="prepend-top">

<legend>班级管理</legend>

<div id="messageBox" class="error" style="display:none">输入有误,请先更正。</div>
<table>
<tr>
<td><label for="name" class="field">班级名称:</label></td>
<td><input id="name" name="name" type="text" value="${clazz.name}" class="required"/></td>
</tr>
<tr>
<td><label for="description" class="field">班级简介:</label></td>
<td><textarea id="description" name="description" style="width:550px;height:45px;" >${clazz.description}</textarea></td>
</tr>
<tr>
<td><label for="culture" class="field">班级文化:</label></td>
<td><textarea id="culture" name="culture" style="width:550px;height:45px;">${clazz.description}</textarea></td>
</tr>
<tr>
<td><label for="teacherWords" class="field">教师心语:</label></td>
<td><textarea id="teacherWords" name="teacherWords" style="width:550px;height:45px;">${clazz.description}</textarea></td>
</tr>
<tr>
<td><label for="name" class="field">班级图片:</label></td>
<td>
<img id="imgUrl" src="${clazz.iconUrl}" width="80" height="60" />
<input type="hidden" value="${clazz.iconUrl}" id="iconUrl" name="iconUrl" />
<input id="filePath" type="file" />
<span style="color:red;font-size:8;">只能上传jpg、png、gif格式的图片</span>
<input type="button" value="上  传 " onclick="uploadPhoto();" />
</td>
</tr>
</table>
</fieldset>
<div>
<input id="submit" class="button" type="submit" value="提 交"/>&nbsp;
<input id="cancel" class="button" type="button" value="返 回" onclick="history.back()"/>
</div>
</form:form>
JS代码function uploadPhoto() {
var filePath = $("#filePath").val();
if(filePath == null) {
alert("请先选择文件再上传!");
return;
}

var suffix = filePath.substring(filePath.length-3, filePath.length);
if(suffix != "jpg" && suffix != "png" && suffix != "gif") {
alert("请上传jpg、png、gif格式的图片!");
return;
}

$.ajaxFileUpload( {
url : context + "/sys/upload",
secureuri : false,
fileElementId : "filePath",
dataType : "json",
success : function(data, status) {
var url = context + "/upload/" + data.result + "." +suffix;
$("#imgUrl").attr('src', url);
$("#iconUrl").attr('value', url);
},
error : function(data, status, e) {
alert(" upload error: " + data + " Status: " + status + " e: " + e);
}
});
}
后台java代码@Controller
@RequestMapping("/sys")
public class UploadController { @RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public String create(RedirectAttributes redirectAttributes, HttpServletRequest request) { String userPath = request.getSession().getServletContext().getRealPath("/") + "/upload";
System.out.println("userUploadPath: " + userPath);
File attachPath = new File(userPath);

if(!attachPath.exists()) {
attachPath.mkdir();
}

UploadHelper helper = new UploadHelper();
helper.setTmpPath(userPath);
helper.setSavePath(userPath);
List<String> resultList = new ArrayList<String>();
String result = "";
Map<String,String> map = new HashMap<String,String>();
try {
resultList = helper.handleUplodFile(request);
map.put("result", resultList.get(0));
result = "{\""+ "result" + "\":\"" + resultList.get(0) + "\"}";
System.out.println("result: " + result);
} catch (FileUploadException e) {
map.put("result", e.getMessage());
e.printStackTrace();
} catch (IOException e) {
map.put("result", e.getMessage());
e.printStackTrace();
}
return result;
}
}--------------------------------------------------------------------
各位大哥大姐,又遇到过类似的没,帮忙一下咯,在此先谢过了
ajaxfileupload数组越界

解决方案 »

  1.   

    form上加一个enctype="multipart/form-data"看下行不行
      

  2.   

    呵呵,已经尝试过在表单添加enctype="multipart/form-data",但这样在提交表单时就传不了参数这里的upload的处理public class UploadHelper {
    private String tmpPath;
    private String savePath;

    /**
     * @return the tmpPath
     */
    public String getTmpPath() {
    return tmpPath;
    } /**
     * @param tmpPath the tmpPath to set
     */
    public void setTmpPath(String tmpPath) {
    this.tmpPath = tmpPath;
    } /**
     * @return the savePath
     */
    public String getSavePath() {
    return savePath;
    } /**
     * @param savePath the savePath to set
     */
    public void setSavePath(String savePath) {
    this.savePath = savePath;
    } public List<String> handleUplodFile(HttpServletRequest request) throws FileUploadException, IOException{
    File tmpDir = new File(getTmpPath());
    File saveDir = new File(getSavePath());

    List<String> result = new ArrayList<String>();
    if (!ServletFileUpload.isMultipartContent(request)) {
    return result;
    }

    DiskFileItemFactory dff = new DiskFileItemFactory();
    dff.setRepository(tmpDir);// 指定上传文件的临时目录
    dff.setSizeThreshold(1024000);// 指定在内存中缓存数据大小,单位为byte
    ServletFileUpload sfu = new ServletFileUpload(dff);// 创建该对象
    FileItemIterator fii;
    fii = sfu.getItemIterator(request);
    while (fii.hasNext()) {
    FileItemStream fis = fii.next();
    if (fis.isFormField() || fis.getName().length() == 0)
    continue;


    String fileName = formatFileName(fis.getName());
    BufferedInputStream in = new BufferedInputStream(fis.openStream());// 获得文件输入流
    File file = new File(saveDir, fileName);
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));// 获得文件输出流
    Streams.copy(in, out, true);// 开始把文件写到你指定的上传文件夹

    result.add(fileName);
    }
    return result;
    }

    private String formatFileName(String fileName){
    return new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + fileName.substring(fileName.lastIndexOf("."));
    //return fileName;
    }
    }
      

  3.   

    谢谢#2楼的回答,我试了,还是报一样的错java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.RangeCheck(ArrayList.java:547)
    at java.util.ArrayList.get(ArrayList.java:322)
    at cn.qtone.yjy.web.UploadController.upload(UploadController.java:53)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      

  4.   

    你给file加一个name属性,我上次碰到过一次没有给file加name,上传不了文件。
      

  5.   

    是不是我在一个project中同时使用了swfupload和ajaxfileupload的原因,他们会有图冲????
      

  6.   

    name也刚刚加了,还是不听话,上传不了
      

  7.   

    这是我以前写过的,看一下对你有没有用。boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
    try {
    FileItemFactory factory = (FileItemFactory) new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> items = upload.parseRequest(request);// 得到所有的文件
    Iterator<FileItem> itr = items.iterator();
    while (itr.hasNext()) {// 依次处理每个文件
    FileItem item = (FileItem) itr.next();
    File savedFile = ......;
    item.write(savedFile);
    }
    ......
      

  8.   

    这个问题应该是由于在一个project中同时使用了swfupload和ajaxfileupload的原因,因为我直接靠代码到没有用swfupload的web project都没问题,还是谢谢楼上的帮忙,只好不用ajaxfileupload,直接用取数据流,就OK了,具体还是有点麻烦的。