el-upload加springboot实现接口转发的多文件上传

wylc123 12天前 ⋅ 20 阅读

1、使用背景

前后端分离的项目,要通过本项目的api调用另一个项目的上传接口,并且实现多文件上传,前端使用el-upload组件。

2、前端代码(vue+element)

<template>
	<el-dialog title="导入切分词语料" :visible.sync="dialogImportVisible" width="30%">
      <el-form ref="form" :model="form" label-width="110px">
        <el-form-item label="语料名称:">
          <el-input size="small" v-model="docTitle" placeholder="请输入语料名称"></el-input>
        </el-form-item>
        <el-form-item label="选择文件:">
          <el-upload
            class="upload-demo"
            action
            :multiple="true"
            accept=".pdf,application/pdf,.txt,.doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
            :before-upload="beforeUpload"
            :on-change="handleUploadFileChange"
            :on-remove="removeFile"
            :auto-upload="false"
            :file-list="fileList"
            ref="docUpload"
          >
            <el-button type="primary" size="small">上传文件</el-button>
            <span class="cg9 margin-left-15 f12">请上传txt或doc或docx或pdf格式的文件,编码格式要求UTF-8</span>
          </el-upload>
        </el-form-item>
        <el-form-item label="输入文本:" v-else>
          <el-input type="textarea" :rows="6" v-model="content"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small"" @click="uploadDocSubmit">确 定(文件)</el-button>
        <el-button size="small" @click="dialogImportVisible = false">取 消</el-button>
      </div>
    </el-dialog>
</template>
function handleUploadFileChange (file, fileList) {
  debugger
  this.fileList = fileList
}
function removeFile (file, fileList) {
  debugger
  this.fileList = fileList
}
function uploadDocs () {
  const loading = this.$loading({
    lock: true,
    text: '正在导入,请稍后......',
    spinner: 'el-icon-loading',
    background: 'rgba(255, 255, 255, 0.5)'
  })
  debugger
  let formData = new FormData()
  if(this.fileList && this.fileList.length>0) {
    for(let f of this.fileList) {
              formData.append("files", f.raw);//需要使用append将文件添加到数据中
            }
  }
  formData.append('title', this.docTitle)
  formData.append('radioCheck', this.radio)

  SegmentApi.uploadTxt(formData)
    .then(resp => {
      if (resp.code === 200 && resp.data && resp.data.code === 200) {
        this.$message.success('导入切分词语料成功')
        loading.close()
        // 上传成功返回到第一页
        this.pageObj.currentPage = 1
        this.fetchCropusList()
      } else {
        loading.close()
        this.$message.warning(resp.data.msg)
      }

      this.$refs.docUpload.clearFiles() // 清空上传列表
      loading.close()
      this.dialogImportVisible = false
    })
    .catch(err => {
      this.$message.error(err.msg || '导入切分词语料失败')
      loading.close()
      this.dialogImportVisible = false
    })
}
function beforeUpload (file,fileList) {
  debugger
  // 判断语料类型
  if (file.type !== 'application/pdf' && file.type !== 'text/plain' && file.type !== 'application/msword' && file.type !== 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
    this.$message.warning('请上传txt或doc或docx或pdf格式的文件!')
    return false
  }
}
function uploadDocSubmit () {
  if (this.docTitle === '') {
    this.$message.warning('请填写语料名称')
    return false
  }
  if (this.$refs.docUpload.uploadFiles.length === 0) {
    this.$message.warning('请选择语料')
    return false
  }
  this.uploadDocs()
  this.centerDialogVisible = false
}

前端接口调用:

// 导入语料
  // 批量导入词条(txt)
  uploadTxt (data) {
    data.append('url', '/Segment/uploadTxt')
    return this.post(
      '/nlpNer/uploadFiles',
      data,
      {},
      {
        'Content-Type': 'multipart/form-data'
      }
    )
  }

3、后端接收前端多文件(转接接口实现),并传输给另一个项目的多文件上传接口

@Controller
@RequestMapping(value = "/nlpNer")
public class NlpNerController extends BaseController {
//实现文件上传的接口地址,配置到配置文件里
	@Value("${nlpNer.url}")
	private String nlpNerPath;
	@ResponseBody
    @RequestMapping(value = "/uploadFiles")
    public BaseResponse<Object> uploadFiles(//@RequestParam("files[]") MultipartFile[] files,
                                           HttpServletRequest request){//,MultipartHttpServletRequest mRequest
        BaseResponse<Object> result = new BaseResponse<Object>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        MultiValueMap<String,MultipartFile> fileMap = multipartHttpServletRequest.getMultiFileMap();
        try {
            String xAuthToken = "";
            Cookie[] cookie = request.getCookies();
            for (int i = 0; i < cookie.length; i++) {
                Cookie cook = cookie[i];
                if (cook.getName().equalsIgnoreCase("DICT_SESSION")) { //获取键
                    xAuthToken = cook.getValue().toString();
                }
            }
            String url = request.getParameter("url");
            Map<String, Object> data = new HashMap<>();
            if ("/autoLable/getEntityByUploadDics".equals(url)) { // 根据导入的词典自动标注
                String corpusId = request.getParameter("corpusId");
                String tags = request.getParameter("tags");
                String dics = request.getParameter("dics");
                data.put("corpusId", corpusId);
                data.put("tags", tags);
                data.put("dics", dics);
            } else if ("/Segment/uploadTxt".equals(url)) { // 导入切分词语料
                String title = request.getParameter("title");
                String radioCheck = request.getParameter("radioCheck");
                data.put("title", title);
                data.put("radioCheck", radioCheck);
            }
            url = nlpNerPath + url;
            Map<String, String> resultDataMap = HttpRequest.sendMultipartFilesPost(url, fileMap, data, -1,xAuthToken);
            if ("200".equals(resultDataMap.get("scode"))) {
                JSONObject jsonObj = JSONObject.parseObject(resultDataMap.get("data"));
                result.setData(jsonObj);
                result.setReturnStatus(ReturnStatus.Success);
                result.setMsg("成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setReturnStatus(ReturnStatus.Error);
            result.setMsg("服务器错误");
        }
        return result;
    }
}

实现接口转发:HttpRequest.java工具类

public class HttpRequest {
    private static final Logger log = LoggerFactory.getLogger(HttpRequest.class);

    /**
     *
     * @param url 请求地址
     * @param fileMap  post提交的多个文件
     * @param params        附带的文本参数
     * @param timeout      请求超时时间(毫秒)
     * @return
     */
    public static Map<String, String> sendMultipartFilesPost( String url, MultiValueMap<String,MultipartFile> fileMap,
                                                             Map<String, Object> params, int timeout,String xAuthToken) {
        Map<String, String> resultMap = new HashMap<String, String>();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("x-auth-token",xAuthToken);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            String fileName = null;
            List<MultipartFile> list = fileMap.get("files");
            if(list!=null && list.size()>0){
                for(MultipartFile file: list){
                    fileName = file.getOriginalFilename();
                    builder.addBinaryBody("files", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
                }
            }
//            Iterator it = fileMap.entrySet().iterator();
//            while(it.hasNext()){
//                MultiValueMap.Entry entry = (MultiValueMap.Entry) it.next();
//                MultipartFile file = (MultipartFile)entry.getValue();
//                fileName = file.getOriginalFilename();
//                builder.addBinaryBody(entry.getKey().toString(), file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
//            }
            //解决中文乱码
            ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                if(entry.getValue() == null)
                    continue;
                // 类似浏览器表单提交,对应input的name和value
                builder.addTextBody(entry.getKey(), entry.getValue().toString(), contentType);
            }
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);// 执行提交

            // 设置连接超时时间
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout)
                    .setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
            httpPost.setConfig(requestConfig);

            HttpEntity responseEntity = response.getEntity();
            resultMap.put("scode", String.valueOf(response.getStatusLine().getStatusCode()));
            resultMap.put("data", "");
            if (responseEntity != null) {
                // 将响应内容转换为字符串
                result = EntityUtils.toString(responseEntity, java.nio.charset.Charset.forName("UTF-8"));
                resultMap.put("data", result);
            }
        } catch (Exception e) {
            resultMap.put("scode", "error");
            resultMap.put("data", "HTTP请求出现异常: " + e.getMessage());

            Writer w = new StringWriter();
            e.printStackTrace(new PrintWriter(w));
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultMap;
    }
}

4、多文件上传接口

@Api(value = "切分词管理控制器")
@Controller
@RequestMapping("/Segment")
public class SegmentController {

	/**
     * 导入切分词语料(上传txt文件,或文本)
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     */
    @SystemControllerLog(description = "切分词-导入切分词语料(上传txt,word文件,或文本)")
    @ApiOperation(value="导入切分词语料(上传txt,word文件,或文本)", notes="导入切分词语料(上传txt文件,或文本)")
    @ResponseBody
    @PostMapping(value = "/uploadTxt")
    public BaseResponse<Object> uploadWord(HttpServletRequest request){//,String title,String radioCheck,String content,MultipartFile mf
        BaseResponse<Object> result = new BaseResponse<>();
        try {
            String filePath = "";
            //0文件,1文本
            String radioCheck = request.getParameter("radioCheck");
            String content_txt = "";
            String title = request.getParameter("title");
            String loginUser = SessionHelper.getLoginUserCode();
            if(StringUtil.isNotBlank(radioCheck)&&"0".equals(radioCheck)){//文件导入
                String encoding="UTF-8";
                MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
                MultiValueMap<String,MultipartFile> fileMap = multipartHttpServletRequest.getMultiFileMap();
                List<MultipartFile> list = fileMap.get("files");
                if(list!=null && list.size()>0){
                    for(MultipartFile mf: list){
                        String fileName = mf.getOriginalFilename();
                        String extName = fileName.substring(fileName.lastIndexOf("."));
                        if(".txt".equals(extName.toLowerCase())){
                            byte[] contentx = mf.getBytes();
                            String encodingx = FileUtil.getEncoding(contentx);
                            Reader reader = new InputStreamReader(mf.getInputStream(), encodingx);
                            BufferedReader br = new BufferedReader( reader);
                            String line;
                            while ((line = br.readLine()) != null) {
                                // 一次读入一行数据
                                if(line!=null && line!=""){
                                    content_txt = content_txt + line;
                                }
                            }
                            reader.close();
                            if(StringUtil.isBlank(content_txt)){
                                result.setCode(205);
                                result.setMsg("请不要导入空文件!");
                                return result;
                            }else {
                                filePath = getFilePath(mf);
                                FileOutputStream outputStream = new FileOutputStream(filePath);
                                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, encoding));
                                String content = new String(contentx, encodingx);
                                writer.write(content);
                                writer.close();
                            }
                        }else if(".doc".equals(extName.toLowerCase())||".docx".equals(extName.toLowerCase())){
                            byte[] content = mf.getBytes();
                            filePath = getFilePath(mf);
                            FileOutputStream outputStream = new FileOutputStream(filePath);
                            outputStream.write(content);
                            outputStream.close();
                            content_txt = content_txt + WordHelper.readWord(filePath);
                        }else if(".pdf".equals(extName.toLowerCase())){
                            byte[] content = mf.getBytes();
                            filePath = getFilePath(mf);
                            FileOutputStream outputStream = new FileOutputStream(filePath);
                            outputStream.write(content);
                            outputStream.close();
                            content_txt = content_txt + PdfReader.getPdfFileText(filePath);
                        }
                    }
                }
            }else{//文本导入
                filePath = getFilePath();
                content_txt = request.getParameter("content");
                boolean flag = FileUtil.writefile(filePath,content_txt);
                if(!flag){
                    result.setCode(204);
                    result.setMsg("文本保存到文件失败!");
                    return result;
                }
            }
            String fileName = filePath.substring(filePath.lastIndexOf("/")+1);
            WordSegmentCorpus wordSegmentCorpus = new WordSegmentCorpus(title,content_txt,fileName, 1, loginUser);
            int flag = wordSegmentCorpusService.addCorpus(wordSegmentCorpus);
            if(flag > 0) {
                log.info("导入成功!");
                result.setCode(200);
//                result.setData(content_txt);
                result.setMsg("导入成功!");
                return result;
            }else {
                log.info("导入失败!");
                result.setCode(201);
                result.setMsg("导入失败!");
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
            result.setMsg("导入失败,服务器错误!");
            return result;
        }
    }
}

 


相关文章推荐
  • 该目录下还没有内容!

全部评论: 0

    我有话说: