SpringBoot使用RestEasy通过post方式上传文件
1.SpringBoot使用RestEasy上传文件
@RestEasyController
@Path("/test")
public class TestController{
private static final Logger logger = LoggerFactory.getLogger(TestController.class);
@POST
@Path("/uploadFile/v1")
@Consumes("multipart/form-data")
public ResponseMsg<Map<String,Object>> fileUpload(MultipartFormDataInput input){
ResponseMsg<Map<String, Object>> responseMsg = new ResponseMsg<>();
try{
Map<String,List<InputPart>> datamap = input.getFormDataMap();
List<InputPart> fileParts = datamap.get("file");
InputStream in;
if(fileParts.size()==1){
InputPart input = fileParts.get(0);
in = inputPart.getBody(InputStream.class,null);
MultivalueMap<String,String> header = inputPart.getHeaders();
String fileName = getFileName(header);
//上传的文件存到本地的路径
String path = "D:\\b";
FileOutputStream fos = new FileOutputStream(path+File.separator+fileName);
byte[] buf = new bytes[1024];
int len = 0;
while((len = in.read(buf)) != -1){
fos.write(buf,0,len);
}
fos.close();
}
responseMsg.setMessage("上传的文件成功!");
}catch(Exception e){
logger.error(e.getMessage(),e);
responseMsg.setMessage("上传的文件失败!");
}
return responseMsg;
}
private String getFileName(MultivalueMap<String,String> header){
String[] contentDisposition = header.getFirst("Content-Disposition").split(";");
for(String filename : contentDisposition){
if(filename.trim().startsWith("filename")){
String[] name = filename.split("=");
String finalFileName = name[1].trim().replaceAll("\"","");
return finalFileName;
}
}
return "";
}
}
2.使用postman测试
3.使用代码调用RestEasy上传文件接口
@GET
@Path("/diaoyongUpload/v1")
@Produces("application/json;charset=UTF-8")
@Consumes("application/json;charset=UTF-8")
public ResponseMsg<Map<String,Object>> diaoyongUpload(){
try{
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target("http://localhost:10008/test/uploadFile/v1");
MultipartFormDataOutput mdo = new MultipartFormDataOutput();
mdo.addFormData("file",new FileInputStream(new File("D:\\a.txt")),MediaType.APPLICATION_OCTET_STREAM_TYPE);
GenericEntity<MultipartFormDataOutput> entity = new GenericEntity<MultipartFormDataOutput>(mdo){};
Response result = target.request().post(Entity.entity(entity,MediaType.MULTIPART_FORM_DATA_TYPE));
responseMsg.setMessage("调用成功!");
}catch(Exception e){
logger.error(e.getMessage(),e);
responseMsg.setMessage("调用失败!");
}
return responseMsg;
}