最近遇到个问题。我用java写的本地文件上传到HDFS上。因为用的WebUploader插件。由前台传送到后台。导致了本地文件的真实路径被浏览器变声fakepath了。想请教下。怎么得到上传附件的真是路径。代码是以上这样的:
前端JS代码:
$(function() {
    var seqId = $("#seqId").val();    var uploader = WebUploader.create({        // swf文件路径
        swf: '${ctxPath}/static/modular/csvattachmentinfo/webuploader-0.1.5/Uploader.swf',        // 文件接收服务端。
        server: Feng.ctxPath+'/csvAttachmentInfo/uploadFile?seqId='+seqId,        // 选择文件的按钮。可选。
        pick:{
            id:'#picker',  //选择文件的按钮
            multiple:false
        },
        // 单个文件最大限制
        // fileSingleSizeLimit :50*1024*1024,
        //单文件上传
        fileNumLimit: 1,
        // 不压缩image, 默认如果是jpeg,文件上传前会压缩一把再上传!
        resize: false,
        duplicate :true
    });    // 当有文件被添加进队列的时候
    uploader.on( 'fileQueued', function( file ) {
        $('#thelist').append( '<div id="' + file.id + '" class="item">' +
            '<h4 class="info">' + file.name + '</h4>' +
            '<p class="state">等待上传...</p>' +
            '</div>' );
    });    //验证文件大小
    uploader.on("error", function (type) {
        if (type == "F_EXCEED_SIZE") {
            layer.msg("文件大小不能超过50M");
        }else if(type == "Q_EXCEED_NUM_LIMIT"){
            layer.msg("只能选择一个文件");
        }else{
            layer.msg("文件出错!错误代码"+type);
        }
    });    // 文件上传过程中创建进度条实时显示。
    uploader.on( 'uploadProgress', function( file, percentage ) {
        var $li = $( '#'+file.id ),
            $percent = $li.find('.progress .progress-bar');        // 避免重复创建
        if ( !$percent.length ) {
            $percent = $('<div class="progress progress-striped active">' +
                '<div class="progress-bar" role="progressbar" style="width: 0%">' +
                '</div>' +
                '</div>').appendTo( $li ).find('.progress-bar');
        }        $li.find('p.state').text('上传中');        $percent.css( 'width', percentage * 100 + '%' );
    });    uploader.on( 'uploadSuccess', function( file,response  ) {
        $( '#'+file.id ).find('p.state').text(response.code);
        parent.Feng_2.info(response.code);
    });    uploader.on( 'uploadError', function( file ) {
        $( '#'+file.id ).find('p.state').text('上传出错');
    });    uploader.on( 'uploadComplete', function( file ) {
        $( '#'+file.id ).find('.progress').fadeOut();
        var win = parent.window['layui-layer-iframe1'].window;
        win.CsvAttachmentInfo.table.refresh();
    });
    //开始上传点击没反应的解决方案,手动绑定上传事件。
    $("#ctlBtn").click(function () {
        uploader.upload();
    });
});后台controller代码:
@RequestMapping(value = "/uploadFile")
    @ResponseBody
    public Map<String,Object> uploadFile(HttpServletRequest request, @RequestParam("file") MultipartFile file, String seqId){
        Map<String,Object> res = new HashMap<String,Object>();
        //Path path1 = null;
        String path = request.getSession().getServletContext().getRealPath(String.valueOf(file));
        //String path = this.getClass().getClassLoader().getResource("file").getPath();
        String serverFilename = null;
        String fileType = null;
        if(!file.isEmpty()) {
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("HHmmssSSS");
            serverFilename = sdf.format(date);
            String fileName=file.getOriginalFilename();
            fileType=fileName.substring(fileName.lastIndexOf(".")+ 1, fileName.length());
        }
        try {
            HdfsUtil.hdfsUpload("/gage/test/matrix/step1_input/",path);
            CsvAttachmentInfo csvAttachmentInfo = new CsvAttachmentInfo();
            csvAttachmentInfo.setCsvAttachmentName(serverFilename+"."+fileType);
            csvAttachmentInfo.setBatchId(seqId);
            csvAttachmentInfo.setDelFlag(0);
            csvAttachmentInfoService.insert(csvAttachmentInfo);
        } catch (IOException e) {
            res.put("code","上传出错");
            e.printStackTrace();
            return res;
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        res.put("code","上传成功");
        return res;
    }HdfsUtil部分代码:
public static boolean hdfsUpload(String destPath,String basePath) throws IOException,URISyntaxException {        //获取配置文件信息
        Configuration conf = new Configuration();
        conf.set("fs.hdfs.impl", "org.apache.hadoop.hdfs.DistributedFileSystem");
        conf.set("fs.defaultFS", HDFSUri);
        //获取文件系统
        FileSystem hdfs = FileSystem.get(conf);
        //文件名称
        Path src = new Path(basePath);
        Path dst = new Path(HDFSUri + destPath);
        if(!hdfs.exists(dst)){
            hdfs.mkdirs(dst);
        }
        hdfs.copyFromLocalFile(src, dst);
        System.out.println("Upload to " + conf.get("fs.defaultFS"));
        FileStatus files[] = hdfs.listStatus(dst);
        for(FileStatus file:files){
            System.out.println(file.getPath());
        }
        return true;
    }
HTML代码:
<div id="uploader" class="wu-example">
                <!--用来存放文件信息-->
                <div id="thelist" class="uploader-list"></div>
                <div class="btns">
                    <div id="picker">选择文件</div>
                    <button id="ctlBtn" class="btn btn-default">开始上传</button>
                </div>
            </div>
错误信息为:
2019-01-16 15:32:05.425  WARN 20196 --- [nio-8080-exec-1] org.apache.hadoop.util.NativeCodeLoader  : Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
java.io.FileNotFoundException: File C:/Users/gff/AppData/Local/Temp/tomcat-docbase.4861895171822099555.8080/org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile@1eeab002 does not exist