Commit 5bca1ceb authored by huangcb's avatar huangcb

新增获取文件数据功能接口

parent e8956856
package com.esv.freight.file.module.download.controller;
import com.alibaba.fastjson.JSONObject;
import com.esv.freight.file.common.response.EResponse;
import com.esv.freight.file.common.validator.groups.ValidatorDetail;
import com.esv.freight.file.module.upload.form.FileForm;
import com.esv.freight.file.module.upload.service.FileMetaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
......@@ -42,4 +44,20 @@ public class DownloadController {
public void directDownload(@PathVariable("id") String id, HttpServletResponse response) {
fileMetaService.directDownload(id, response);
}
/**
* description 获取文件数据
* param [fileForm]
* return com.esv.freight.file.common.response.EResponse
* author Administrator
* createTime 2020/04/14 20:33
**/
@PostMapping("/getFileData")
public EResponse getFileData(@RequestBody @Validated(ValidatorDetail.class) FileForm fileForm) {
String fileData = fileMetaService.getFileData(fileForm);
JSONObject data = new JSONObject();
data.put("fileData", fileData);
return EResponse.ok(data);
}
}
package com.esv.freight.file.module.upload.form;
import com.esv.freight.file.common.validator.groups.ValidatorDelete;
import com.esv.freight.file.common.validator.groups.ValidatorDetail;
import com.esv.freight.file.common.validator.groups.ValidatorInsert;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
......@@ -19,7 +20,7 @@ import javax.validation.constraints.NotBlank;
@Data
public class FileForm {
@Length(max = 2, message = "参数fileType长度不合法", groups = {ValidatorInsert.class})
@Length(max = 10, message = "参数fileType长度不合法", groups = {ValidatorInsert.class})
@NotBlank(message = "参数fileType不能为空", groups = {ValidatorInsert.class})
private String fileType;
......@@ -30,7 +31,7 @@ public class FileForm {
@NotBlank(message = "参数fileName不能为空", groups = {ValidatorInsert.class})
private String fileName;
@Length(max = 64, message = "参数id长度不合法", groups = {ValidatorDelete.class})
@NotBlank(message = "参数id不能为空", groups = {ValidatorDelete.class})
@Length(max = 64, message = "参数id长度不合法", groups = {ValidatorDelete.class, ValidatorDetail.class})
@NotBlank(message = "参数id不能为空", groups = {ValidatorDelete.class, ValidatorDetail.class})
private String id;
}
......@@ -44,5 +44,14 @@ public interface FileMetaService extends IService<FileMetaEntity> {
**/
void deleteFile(FileForm fileForm) throws EException;
/**
* description 获取文件数据
* param [fileForm]
* return java.lang.String
* author Administrator
* createTime 2020/04/14 20:23
**/
String getFileData(FileForm fileForm) throws EException;
}
......@@ -207,10 +207,6 @@ public class FileMetaServiceImpl extends ServiceImpl<FileMetaDao, FileMetaEntity
updateEntity.setDeleted(DbDeletedEnum.YES.getCode());
updateEntity.setDeleteTime(new Date());
updateEntity.setFileId(fileId);
// FileMetaEntity updateWrapperEntity = new FileMetaEntity();
// updateWrapperEntity.setDeleted(DbDeletedEnum.NO.getCode());
// QueryWrapper<FileMetaEntity> updateWrapper = new QueryWrapper<>(updateWrapperEntity);
// int flag = this.baseMapper.update(updateEntity, updateWrapper);
int flag = this.baseMapper.logicDelete(updateEntity);
if (0 == flag) {
throw new EException("文件删除失败");
......@@ -225,6 +221,41 @@ public class FileMetaServiceImpl extends ServiceImpl<FileMetaDao, FileMetaEntity
}
}
@Override
public String getFileData(FileForm fileForm) throws EException {
// 校验文件是否存在
String fileId = fileForm.getId();
FileMetaEntity queryEntity = new FileMetaEntity();
queryEntity.setFileId(fileId);
QueryWrapper<FileMetaEntity> queryWrapper = new QueryWrapper<>();
queryWrapper.setEntity(queryEntity);
FileMetaEntity fileMetaEntity = this.getOne(queryWrapper);
if (null == fileMetaEntity) {
throw new EException(1001, "文件不存在");
}
// 获取文件数据
String fileData;
Query query = Query.query(Criteria.where("_id").is(fileId));
GridFSFile gridFSFile = gridFsTemplate.findOne(query);
if (null == gridFSFile) {
throw new EException("文件数据不存在");
}
GridFSBucket bucket = GridFSBuckets.create(mongoDbFactory.getDb());
GridFSDownloadStream gridFSDownloadStream = bucket.openDownloadStream(gridFSFile.getObjectId());
GridFsResource gridFsResource = new GridFsResource(gridFSFile, gridFSDownloadStream);
try {
InputStream inputStream = gridFsResource.getInputStream();
byte[] bytes = IOUtils.toByteArray(inputStream);
fileData = Base64.getEncoder().encodeToString(bytes);
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new EException("服务内部错误");
}
return fileData;
}
/**
* description 删除MongoDB文件
* param [id]
......
......@@ -9,7 +9,6 @@ import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
......@@ -17,7 +16,6 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;
import java.io.ByteArrayOutputStream;
......@@ -39,7 +37,6 @@ import java.util.Base64;
@SpringBootTest
@Slf4j
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@Transactional
public class UploadControllerTest {
@Autowired
......@@ -47,6 +44,10 @@ public class UploadControllerTest {
private MockMvc mockMvc;
private static String fileId;
private static String fileUrl;
@Before
public void before() {
log.info("=================================== Test Start ===================================");
......@@ -59,7 +60,6 @@ public class UploadControllerTest {
}
@Test
@Rollback
public void a1_uploadSingleFile_success_test() throws Exception {
String url = "/upload/single";
JSONObject reqJson = new JSONObject();
......@@ -91,10 +91,11 @@ public class UploadControllerTest {
JSONObject result = JSONObject.parseObject(responseStr);
Assert.assertEquals(ECode.SUCCESS.code(), result.getIntValue("code"));
fileId = result.getJSONObject("data").getString("id");
fileUrl = result.getJSONObject("data").getString("url");
}
@Test
@Rollback
public void b1_uploadSingleFile_file_type_error_test() throws Exception {
String url = "/upload/single";
JSONObject reqJson = new JSONObject();
......@@ -129,7 +130,6 @@ public class UploadControllerTest {
}
@Test
@Rollback
public void b2_uploadSingleFile_file_size_error_test() throws Exception {
String url = "/upload/single";
JSONObject reqJson = new JSONObject();
......@@ -162,4 +162,60 @@ public class UploadControllerTest {
JSONObject result = JSONObject.parseObject(responseStr);
Assert.assertEquals(1002, result.getIntValue("code"));
}
@Test
public void c1_directDownload_success_test() throws Exception {
String[] datas = fileUrl.split("direct");
String dUrl = datas[1];
String url = "/download/direct/"+dUrl;
mockMvc.perform(MockMvcRequestBuilders.get(url))
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
}
@Test
public void c2_getFileData_success_test() throws Exception {
String url = "/download/getFileData";
JSONObject reqJson = new JSONObject();
// 构造数据
reqJson.put("id", fileId);
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post(url)
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
.content(reqJson.toJSONString()))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
String responseStr = mvcResult.getResponse().getContentAsString();
log.info(responseStr);
JSONObject result = JSONObject.parseObject(responseStr);
Assert.assertTrue(result.getJSONObject("data").containsKey("fileData"));
}
@Test
public void d1_deleteSingleFile_success_test() throws Exception {
String url = "/delete/single";
JSONObject reqJson = new JSONObject();
// 构造数据
reqJson.put("id", fileId);
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post(url)
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
.content(reqJson.toJSONString()))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
String responseStr = mvcResult.getResponse().getContentAsString();
log.info(responseStr);
JSONObject result = JSONObject.parseObject(responseStr);
Assert.assertEquals(ECode.SUCCESS.code(), result.getIntValue("code"));
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment