后端代码发送请求调用带MultipartFile参数的接口
程序员文章站
2022-06-20 18:27:45
...
【说明】:以下源码是文件服务组件的上传和下载接口控制层代码;设计是使用minio的接口实现上传和下载文件;将文件存入minio服务端,然后再从minio服务端下载。
【注意】:
- 下载接口如果将byte[]放入实体返回类中,spring boot将会对其进行base64加密处理。
- @CrossOrigin(origins = “*”, maxAge = 3600)注解可以解决跨域问题
- MultipartFile 类型入参在后端调用情况可以参见测试类的test2和test3方法
1. 上传文件接口+下载接口
@CrossOrigin(origins = "*", maxAge = 3600)
@Api(tags="文件服务操作")
@RequestMapping("/run/file-server/v1/file_server/file_mgmt")
@RestController
public class MinioController {
//默认的userId ="0000"
private final Logger logger = LoggerFactory.getLogger(getClass());
private static final String CBB_FILE_SERVER = "cbb-content-";
private static final String CBB_NAME_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static final String CBB_FILE_NAME_EXT = ".zip";
@ApiOperation("上传文件")
@PostMapping(value = "/upload", headers = "content-type=multipart/form-data")
public RestResult uploadFile(HttpServletRequest request, HttpServletResponse response,
UploadFile uFile, MultipartFile file) {
logger.info("Params:{}", JSON.toJSON(request.getParameterMap()));
if (file== null) {
return RestResult.error("文件不能为空");
}
if(StringUtils.isBlank(uFile.getBucketName())){
uFile.setBucketName(ConfigUtil.getBucketName());
}
RequestHeader requestHeader = RequestHeader.getHead(request);
//先给你一个默认值
String userId = "0000";
if (requestHeader != null && requestHeader.getUserId() != null)
userId = requestHeader.getUserId();
try {
RestResult upload = MinioUtil.upload(uFile.getBucketName(), userId, uFile.getFileName(), file, uFile.getContentType(), uFile.getFileAttribute(), uFile.getSaveCycle());
if (upload.getCode() == 200) {
ResponseHeader header = new ResponseHeader(200, "上传文件", null, null);
ResponseHeader.setResponseHeader(response, header);
return upload;
} else {
ResponseHeader header = new ResponseHeader(500, "上传文件", null, null);
ResponseHeader.setResponseHeader(response, header);
return RestResult.error("上传失败");
}
} catch (Exception e) {
e.printStackTrace();
ResponseHeader header = new ResponseHeader(500, "上传文件", null, null);
ResponseHeader.setResponseHeader(response, header);
return RestResult.error("上传失败");
}
}
@ApiOperation("浏览直接下载文件")
@GetMapping("/download")
public ResponseEntity<byte[]> downloadFile(HttpServletRequest request, HttpServletResponse response, DeleteFile body) throws IOException, XmlPullParserException, NoSuchAlgorithmException, InvalidKeyException, InvalidArgumentException, ErrorResponseException, NoResponseException, InvalidBucketNameException, InsufficientDataException, InternalException {
HttpHeaders headers = new HttpHeaders();
if(StringUtils.isBlank(body.getBucketName())){
body.setBucketName(ConfigUtil.getBucketName());
}
String fileNme = MinioUtil.getFileName(body.getFileId());
headers.add("Content-Disposition", "attachment;filename=" + fileNme);
ByteArrayOutputStream bos = MinioUtil.download(body.getBucketName(),body.getFileId());
return new ResponseEntity<byte[]>(bos.toByteArray(), headers, HttpStatus.OK);
}
}
2.实体入参
@ApiModel(description = "上传实体")
public class UploadFile implements Serializable {
@ApiModelProperty(value = "文件名称(和上传文件名称一致)", required = true,example = "文件服务接口.docx", notes = "文件名称(和上传文件名称一致)")
private String fileName;
@ApiModelProperty(value = "文件属性(R、W、RW)", example = "RW", notes = "文件属性(R、W、RW)")
private String fileAttribute;
@ApiModelProperty(value = "保存周期",example = "0", notes = "保存周期")
private Integer saveCycle;
// @ApiModelProperty(value = "文件数组", required = true,example = "File", notes = "文件数组,可以传String,也可以是byte[]")
// private MultipartFile file;//原来是MultipartFile
@ApiModelProperty(value = "内容类型", example = "application/octet-stream", notes = "内容类型")
private String contentType;
@ApiModelProperty(value = "minio的桶名",required = false, example = "cbbbucket", notes = "minio的桶名")
private String bucketName;
}
3.调用示例
package com.run.cbb.fileserver.controller;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
/**
* @ClassName FileServerTest
* @Description TODO
* @Author yexinfa
* @Date 2020/2/26 0026 18:21
* @Version 1.0
*/
public class FileServerTest {
/**
* @Author yexinfa
* @Description 测试下载接口
* @Date 2020/2/26 0026 22:42
* @Param
* @Return
*/
public void test1() {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set("Run-Request-Header", "{\"snId\":\"20200209234201989124\",\"systemId\":\"0000\",\"cbbId\":\"80000300211\",\"userId\":\"1234\",\"encryptionId\":\"0\",\"userToken\":\"\",\"systemToken\":\"\"}");
org.springframework.http.HttpEntity<Object> requestEntity = new org.springframework.http.HttpEntity<Object>(headers);
ResponseEntity<byte[]> exchange = restTemplate.exchange("http://127.0.0.1:8199/run/file-server/v1/file_server/file_mgmt/download?fileId=cbbbucket_0000_9d8fdde49464b4ba8c41165f90825052_0_1582711352422", HttpMethod.GET, requestEntity, byte[].class);
byte[] body = exchange.getBody();
}
/**
* @Author yexinfa
* @Description 测试上传接口
* @Date 2020/2/26 0026 22:42
* @Param
* @Return
*/
public void test2() {
RestTemplate restTemplate = new RestTemplate();
//filePath,即文件路径
FileSystemResource resource = new FileSystemResource(new File("E:\\test.txt"));
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
// 此files对应请求接口方法参数变量,需一致,否则对方接口接不到参数
param.add("file", resource);
param.add("fileName", "test.txt");
// 根据restTemplate来发送请求
Object object = restTemplate.postForObject("http://127.0.0.1:8199/run/file-server/v1/file_server/file_mgmt/upload", param, Object.class);
System.out.println();
}
public static void main(String[] args) throws IOException {
new FileServerTest().test3("测试.json", "R", "application/octet-stream", "cbbbucket", "我好累啊".getBytes());
}
/**
* @Author yexinfa
* @Description 测试上传接口
* @Date 2020/2/26 0026 23:21
* @Param
* @Return
*/
public void test3(String fileName, String fileAttribute, String contentType, String bucketName, byte[] bytes) {
Map<String, Object> data = new HashMap<String, Object>();
String url = "http://127.0.0.1:8199/run/file-server/v1/file_server/file_mgmt/upload";//服务端要调用的外部接口
Map<String, String> resultMap = new HashMap<String, String>();
//httpclients构造post请求
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Run-Request-Header","{\"snId\":\"20200209234201989124\",\"systemId\":\"0000\",\"cbbId\":\"80000300211\",\"userId\":\"1234\",\"encryptionId\":\"0\",\"userToken\":\"\",\"systemToken\":\"\"}");
//HttpMultipartMode.RFC6532参数的设定是为避免文件名为中文时乱码
MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
builder.addBinaryBody("file", bytes, ContentType.MULTIPART_FORM_DATA, fileName);// 设置上传文件流(需要是输出流),设置contentType的类型
builder.addTextBody("fileAttribute", fileAttribute);//post请求中的其他参数
builder.addTextBody("contentType", contentType);//post请求中的其他参数
builder.addTextBody("bucketName", bucketName);//post请求中的其他参数
builder.addTextBody("fileName", fileName);//post请求中的其他参数
builder.addTextBody("saveCycle", "2");//post请求中的其他参数
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);// 执行提交
HttpEntity responseEntity = response.getEntity();//接收调用外部接口返回的内容
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 返回的内容都在content中
String str = getHttpEntity(response);
System.out.println(str);
}
} catch (Exception e) {
} finally {//处理结束后关闭httpclient的链接
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static String getHttpEntity(HttpResponse response) {
String line=null;
JSONObject resultJsonObject=null;
StringBuilder entityStringBuilder=new StringBuilder();
try {
BufferedReader b = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"),8*1024);
while ((line=b.readLine())!=null) {
entityStringBuilder.append(line+"/n");
}
//利用从HttpEntity中得到的String生成JsonObject
// String s = entityStringBuilder.toString();
// resultJsonObject = JSONObject.parseObject(entityStringBuilder.toString());
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return entityStringBuilder.toString();
}
}
上一篇: aardio初探之基本语法
下一篇: Kotlin之基本语法