Java实现文件上传

上传代码分为web端和后端,注意事项已标明





//Java后端代码
//需要的jar包 commons-fileupload-1.2.2.jar,commons-io-2.0.1.jar
    //初始化工具
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    FileOutputStream fileOutputStream = null;
    InputStream inputStream = null;
    String imagePath = null;
        try {
            @SuppressWarnings("unchecked")
            //解析请求
            List fileItems = servletFileUpload.parseRequest(request);
            for (FileItem fileItem : fileItems) {
                if (fileItem.isFormField()) {
                    // 普通form表单域
                    String fieldName = fileItem.getFieldName();//得到表单中input的name
                    if("username".equals(fieldName)){
                        user.setUsername(fileItem.getString());
                    }else if("age".equals(fieldName)){
                        System.out.println("age" + fileItem.getString());
                            if(fileItem.getString() != null){
                                user.setAge(new Integer(fileItem.getString()));
                            }
                    }else if("gender".equals(fieldName)){
                        user.setGender(new Integer(fileItem.getString()));
                    }else if("mail".equals(fieldName)){
                        user.setMail(fileItem.getString());
                    }else if("tel".equals(fieldName)){
                        user.setTel(fileItem.getString());
                    }
                } else {
                    // 不是普通表单域,上传的文件
                    inputStream = fileItem.getInputStream();//获取文件输入流
                    byte[] bytes = new byte[1024];//缓冲区
                    Date date = new Date();
                    imagePath = request.getServletContext().getRealPath("images") + "\\" + date.getTime() + ".jpg";
                    File file = new File(imagePath);
                    fileOutputStream = new FileOutputStream(file);
                    int flag2 = 0;
                    while ((flag2 = inputStream.read(bytes)) != -1) {
                        fileOutputStream.write(bytes);
                    }
                }
            }
            imagePath = imagePath.substring(imagePath.lastIndexOf("\\") + 1, imagePath.length());
            //设置文件路径
            user.setImage(imagePath);
            //更新用户信息
            int updateFlag = userService.update(user);
            //关闭输入输出流
            fileOutputStream.close();
            inputStream.close();

            } catch (org.apache.commons.fileupload.FileUploadException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

你可能感兴趣的:(文件上传)