element--upload上传 配合 java后台

后台使用java,代码如下:

@ResponseBody
    @RequestMapping(params = "method=uploadFile")
    public String uploadFile( @RequestParam("file") List<MultipartFile> file, HttpServletRequest request ) {
        //把文件放在部署路径下的用户ID文件夹中
        String webPath = request.getSession().getServletContext().getRealPath("/");
        Map uploadPath = request.getParameterMap();
        String userId = ((String[]) uploadPath.get("userId"))[0];
        String filePath = "uploaddir/" + userId + "/";

        File dir = new File(webPath+filePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        List<Map<String,Object>> resultList = new ArrayList<>();
        Map<String, Object> result = null;
        Map<String, Object> resultmap = new HashMap<>();
        try {
            for(MultipartFile myfile : file){

                String filename = getFilename(myfile.getOriginalFilename());
                String newFileName = System.currentTimeMillis() + filename.substring(filename.lastIndexOf("."));
                String uuid= AppUtil.getUUID();
                //上传文件
                File tfile = new File(webPath+filePath, newFileName);
                myfile.transferTo(tfile);
                //将文件名和文件路径返回
                result = new HashMap<String, Object>();
                result.put("ID", uuid);// 文件添加一个ID
                result.put("filename", filename);//原文件名
                result.put("newFileName", newFileName);//新文件名
                result.put("filepath", filePath + newFileName);//文件路径
                result.put("fullfilepath", webPath+filePath + newFileName);//文件全路径

                resultList.add(result);
            }
            resultmap.put("success", "1");
            resultmap.put("list", resultList);

        } catch (IOException e) {
            resultmap.put("success", "0");
            logger.error(e.getMessage());
        }
        String str = JSON.toJSONString(resultmap, SerializerFeature.DisableCircularReferenceDetect);
        logger.debug("结果:{}", str);// debug 输出结果
        return str;
    }


/**
     * 处理文件名中的特殊字符
     * @param oriFilename
     * @return
     */
    private String getFilename(String oriFilename){
        //将特殊字符[]英文括号,处理成中文【】
        String filename = oriFilename.replaceAll("\\[","【").replaceAll("\\]","】");
        //将文件名中的空格去掉
        filename = filename.replaceAll(" ","");

        return filename;

    }

删除已上传的文件

public Map<String, Object> deleteFile(ParameterVO parameterVO) {
  HashMap<String, Object> result = new HashMap<>();
    result.put("success", "1");
    Map<String, Object> paramMap = parameterVO.getDimensions();
    String filePath = paramMap.get("UP_FILE").toString();  //拿到文件的路径
    try{
        File fileTemp = new File(filePath);
        if(fileTemp.exists()){
            fileTemp.delete();
        }
    }catch (Exception e){
        result.put("success", "0");
        logger.debug(e.getMessage());
    }
    return result;
}

前端代码:

<el-form-item label="文件上传" prop="">
    <el-upload
             class="upload-demo"
             ref="upload"
             :action="fileUpload.url"
             :data = 'fileUpload.data'
             :auto-upload="false"
             :on-success="file_success"
             :on-error="file_erorr"
             :on-remove = 'deleteFile'
             :limit="1"
             :on-exceed="handleExceed"
             :file-list="fileList"
     >
         <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
     </el-upload>
 </el-form-item>

js代码:

submit(){ //手动触发上传
	this.$refs.upload.submit(); // 上传文件
},
handleExceed(){
	this.$message.warning('仅允许上传一个文件!')
},
file_success: function(file){
    this.fileMsg.FILE_NAME = file.list[0].newFileName; // 文件名
    this.fileMsg.OLD_FILE_NAME = file.list[0].filename; // 文件名
    this.fileMsg.UP_FILE = file.list[0].fullfilepath; // 文件路径
    this.fileMsg.ID = file.list[0].ID; // 文件ID
},
file_erorr: function(){
    this.$message.error('上传失败!');
},
deleteFile: function(file, fileList){
    if(file && file.status==="success"){
    /******              *******/
       if (data.success == '1'){
           that.$message({
               message: '删除成功!',
               type: 'success'
           });
       }else {
           that.$message.error('删除失败!');
       }
    }
},
发布了40 篇原创文章 · 获赞 13 · 访问量 4万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 书香水墨 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览