最近在手机上传文件时,由于手机的插件使用的是原生的流形式进行的上传,导致使用Spring的上传组件不能使用,所以就根据HTTP协议的格式,自己开发了一个读取文件流的上传文件方法,其中发现,手机端采用android和苹果时,头信息不一样,找了好久最终采用http协议上传时,空行作为标准进行文件内容和头的分割,即适配不同终端的上传;另外,再上传文件时,如果采用字符流,读出来的图片文件都是坏的即打不开的,所以都是采用字节流进行图片文件的上传。如下是代码(仅供参考):

@Note(note = "bigAnt:servlet上传文件", author = "zhangwenbo")
    @RequestMapping({ "modifyPictureByStream2" })
    @ResponseBody
    public SimpleMessage<Object> modifyPictureByStream2(HttpServletRequest req, HttpServletResponse response) {
        this.logger.info("modifyHeaderPicture has invoked.filename is ");

        SimpleMessage<Object> sm = new SimpleMessage<Object>();

        InputStream in = null;

        RandomAccessFile accessFile = null;

        ByteArrayOutputStream outputStream = null;

        FileOutputStream fileout = null;

        File tmpFile = null, fileIO = null;

        try {
            // 获取文件上传时的标记
            String boundaryText = req.getContentType().substring(req.getContentType().indexOf("boundary=") + 9);

            // 先以文本格式缓存文件
            in = req.getInputStream();

            tmpFile = File.createTempFile(UUID.randomUUID().toString(), ".txt");

            if (tmpFile.exists()) {
                tmpFile.createNewFile();
            }

            logger.info("cache file path is :" + tmpFile.getPath());

            fileout = new FileOutputStream(tmpFile);

            byte[] tmp_byte = new byte[1024];

            int tmp = -1;

            while ((tmp = in.read(tmp_byte)) > -1) {
                fileout.write(tmp_byte, 0, tmp);
            }

            fileout.flush();

            fileout.close();

            // 从文件内容中分析数据内容
            accessFile = new RandomAccessFile(tmpFile, "r");

            outputStream = new ByteArrayOutputStream();

            String line = accessFile.readLine();

            boolean contentBegin = false;

            boolean hasfileName = false;

            String filename = "";

            while (true) {
                if (!hasfileName) {
                    int filename_index = line.indexOf("filename=\"");

                    if (filename_index > -1) {
                        contentBegin = true;

                        filename = line.substring(filename_index + 10, line.length() - 1);

                        System.out.println("filename is " + filename);

                        while (!"".equals(line.trim())) {// 此处就是一空行为标记,如果以其他的为标记,可能会因为头内容不一样导致,读取失败
                            line = accessFile.readLine();
                        }
                        hasfileName = true;

                        logger.info("the upload filename is :" + filename);

                        continue;
                    }
                    line = accessFile.readLine();
                }

                if (contentBegin) {
                    byte[] temp_byte = new byte[1024];

                    int byte_len = -1;

                    while ((byte_len = accessFile.read(temp_byte)) > -1) {

                        String con_temp = new String(temp_byte, 0, byte_len);

                        if (con_temp.indexOf(boundaryText) > -1) {
                            break;
                        }
                        outputStream.write(temp_byte, 0, byte_len);
                    }
                    break;
                }
            }

            // 恢复上传文件的类型
            int filename_index = filename.indexOf(".");

            fileIO = File.createTempFile(filename.substring(0, filename_index), filename.substring(filename_index));

            if (!(fileIO.exists())) {
                fileIO.createNewFile();
            }

            logger.info("target file filepath:" + fileIO.getPath());

            fileout = new FileOutputStream(fileIO);

            byte[] tem_byte = outputStream.toByteArray();

            System.out.println("write file length is :" + tem_byte.length);

            fileout.write(tem_byte);

            fileout.flush();

            // 开始上传文件到目标服务器
            Map<String, Object> postBody = new HashMap<String, Object>();

            postBody.put("loginname", req.getSession().getAttribute("sessionUserId"));

            BigAntBaseRes uploadResult = BigAntClient.getInstance().uploadPicture(postBody, filename, fileIO);

            this.logger.info("upload return msg is " + uploadResult);

            if (null != uploadResult) {
                if ("1".equals(uploadResult.getStatus().trim()))
                    sm.set("data", uploadResult.getData());
                else
                    sm.set("message", uploadResult.getMsg());
            } else {
                sm.set("message", "upload fail");
            }

        } catch (IOException e) {
            logger.info("upload the file fail.", e);

            sm.set("message", "upload fail");
        } finally {
            try {
                // 删除临时文件
                if (tmpFile.exists()) {
                    tmpFile.delete();
                }

                if (fileIO.exists()) {
                    fileIO.delete();
                }

                if (null != in) {
                    in.close();
                }

                if (null != fileout) {
                    fileout.close();
                }

                if (null != accessFile) {
                    accessFile.close();
                }

                if (null != outputStream) {
                    outputStream.close();
                }
            } catch (Exception e2) {
                logger.info("release resource fail.", e2);
            }
        }
        return sm;
    }