java文件上传
package com.lanxum.domas.controller;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import com.lanxum.domas.config.ParamConfig;
import com.lanxum.domas.config.ResponseMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
@RestController
@Slf4j
@CrossOrigin
@RequestMapping("upload")
public class FileUploadController {
@Autowired
private ParamConfig paramConfig;
@PostMapping("batch")
public ResponseEntity<Map<String, Object>> batch(@RequestParam("pcl") MultipartFile pcl, @RequestParam("xml") MultipartFile xml) {
try {
if(pcl.isEmpty()){
return ResponseEntity.status(HttpStatus.HTTP_OK)
.body(new ResponseMap(HttpStatus.HTTP_BAD_REQUEST, "pcl is empty", "").getResponseMap());
}
if(xml.isEmpty()){
return ResponseEntity.status(HttpStatus.HTTP_OK)
.body(new ResponseMap(HttpStatus.HTTP_BAD_REQUEST, "xml is empty", "").getResponseMap());
}
String pclName = pcl.getOriginalFilename();
String xmlName = xml.getOriginalFilename();
String pclSavePath = paramConfig.getPrintFilePath() + File.separator + pclName;
String xmlSavePath = paramConfig.getPrintFilePath() + File.separator + xmlName;
File pclDest = new File(pclSavePath);
File xmlDest = new File(xmlSavePath);
pcl.transferTo(pclDest);
xml.transferTo(xmlDest);
return ResponseEntity.status(HttpStatus.HTTP_OK)
.body(new ResponseMap(HttpStatus.HTTP_OK, "success", "").getResponseMap());
} catch (Exception e){
e.printStackTrace();
return ResponseEntity.status(HttpStatus.HTTP_OK)
.body(new ResponseMap(HttpStatus.HTTP_INTERNAL_ERROR, "unkonw error", "").getResponseMap());
}
}
public static void main(String[] args){
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("pcl", FileUtil.file("/usr/test.txt"));
paramMap.put("xml", FileUtil.file("/usr/test1.txt"));
String result = HttpUtil.post("http://localhost/upload/batch", paramMap);
}
}