ajax上传文件到服务器

1、图片base64上传注意的地方就是传到后台需要截取一部分才能转换为图片,用到ac里的getPicture,后台就需要处理传过来的字符串 前面是格式类型你会发现逗号前面都是多余的,所以截取逗号以后的那一串然后用base64解析成图片。

2、文件的上传,ac都是ajax提交数据,multipart/form-data,我把代码贴一下,希望能帮助一些人。
前端代码很简单:

    api.ajax({
                                                                url: 'http://192.168.18.53:8080/router?method=uploadAmrFile&name=haha&format=json&v=1.0',
                                                                method: 'post',
                                                                timeout: 90,
                                                                dataType: 'json',
                                                                returnAll:false,
                                                                data:{
                                                                    files:{file:"文件路径"}
                                                                }
 });

 底层架构就不说了,后台代码参考一下吧。
后端接收文件处理代码:(HttpServletRequest)

    public class UploadFileHessian {
            protected Logger log = Logger.getLogger(this.getClass());
            //构造类
            class Position {
                    int begin;
                    int end;
                    public Position(int begin, int end) {
                        this.begin = begin;
                        this.end = end;
                    }
            }
           
            //转换文件
            protected void processRequest(HttpServletRequest request,String path)throws ServletException, IOException {
                    //读取请求Body
                    byte[] body = readBody(request);
                    //取得所有Body内容的字符串表示
                    String textBody = new String(body);
                    //上传文件名称
                    String fileName = getFileName(textBody);
                    //取得文件开始与结束位置
                    Position p = getFilePosition(request, textBody);
                    //输出至文件
                    String path1 = writeTo(fileName, body, p,path);
                    //String path2 = "E:\\aa\\1395047224460.mp3";  
                    //changeToMp3(path1, path2);
            }
            //读取文件
            private byte[] readBody(HttpServletRequest request) throws IOException {
                    //获取请求文本字节长度
                    int formDataLength = request.getContentLength();
                    //取得ServletInputStream输入流对象
                    DataInputStream dataStream = new DataInputStream(request.getInputStream());
                    byte body[] = new byte[formDataLength];
                    int totalBytes = 0;
                    while (totalBytes < formDataLength) {
                        int bytes = dataStream.read(body, totalBytes, formDataLength);
                        totalBytes += bytes;
                    }
                    return body;
            }
            //获取内容位置
            private Position getFilePosition(HttpServletRequest request, String textBody) throws IOException {
                    //取得文件区段边界信息
                    String contentType = request.getContentType();
                    String boundaryText = contentType.substring(contentType.lastIndexOf("=") + 1, contentType.length());
                    //取得实际上传文件的起始与结束位置
                    int pos = textBody.indexOf("filename=\"");
                    //TODO:这里根据返回的报文处理相应的长度  这里只需要获取内容不需要报文在内
                    pos = textBody.indexOf("\n", pos) + 1;
                    pos = textBody.indexOf("\n", pos) + 1;
                    pos = textBody.indexOf("\n", pos) + 1;
                    pos = textBody.indexOf("\n", pos) + 1;
                   
                    int boundaryLoc = textBody.indexOf(boundaryText, pos) - 4;
                    int begin = ((textBody.substring(0, pos)).getBytes()).length;
                    int end = ((textBody.substring(0, boundaryLoc)).getBytes()).length;
                   
                    return new Position(begin, end);
            }
            //获取文件名称
            private String getFileName(String requestBody) {
                    String fileName = requestBody.substring(requestBody.indexOf("filename=\"") + 10);
                    fileName = fileName.substring(0, fileName.indexOf("\n"));
                    fileName = fileName.substring(fileName.indexOf("\n") + 1, fileName.indexOf("\""));
                    return fileName;
            }
            //保存文件
            private String writeTo(String fileName, byte[] body, Position p,String path) throws IOException {
                    FileOutputStream fileOutputStream = new FileOutputStream(path + fileName);
                    fileOutputStream.write(body, p.begin, (p.end - p.begin));
                    fileOutputStream.flush();
                    fileOutputStream.close();
                    return path + fileName;
            }
            //转换mp3
            public void changeToMp3(String sourcePath, String targetPath) {  
            File source = new File(sourcePath);  
            File target = new File(targetPath);  
            AudioAttributes audio = new AudioAttributes();  
            Encoder encoder = new Encoder();  
      
            audio.setCodec("libmp3lame");  
            EncodingAttributes attrs = new EncodingAttributes();  
            attrs.setFormat("mp3");  
            attrs.setAudioAttributes(audio);  
            try {  
                encoder.encode(source, target, attrs);  
            }catch (Exception e) {  
                e.printStackTrace();  
            }
        }
            //上传语音
        public Object uploadFile(UploadAmrFileRequest request){
                    BaseResponse response = new BaseResponse();
                    HttpServletRequest req = (HttpServletRequest) request.getRopRequestContext().getRawRequestObject();
                    StringBuffer sb = new StringBuffer();
                   
            Enumeration<?> en = req.getHeaderNames();  
            while (en.hasMoreElements()) {  
                String name = (String) en.nextElement();
                String value = req.getHeader(name);
                sb.append(name + "=" + value + "\r\n");  
            }
            System.out.println(sb.toString());
            
            ClassPathResource outFile = new ClassPathResource("/");
                    String root;
                    try {
                            root = outFile.getFile().getParent().replace("\\WEB-INF", "").replace("/WEB-INF", "");
                            String path = root+"\\upload\\";
                            processRequest(req,path);
                    } catch (Exception e) {
                            e.printStackTrace();
                    }
            return response;  
        }
    }

 

posted @ 2016-10-20 14:27  智昕  阅读(885)  评论(0编辑  收藏  举报