restful批量上传文件_restful api上传文件(基础)-springboot

基于restful api格式的文件上传(只是上传到本地):

package com.nxz.controller;

import com.nxz.entity.FileInfo;

import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;

import java.io.IOException;

import java.util.Date;

@RestController

@RequestMapping("/file")

public class FileController {

@PostMapping

public FileInfo update(MultipartFile file) throws IOException {

System.out.println(file.getName());

System.out.println(file.getOriginalFilename());

System.out.println(file.getSize());

String holder = "G:\\0001-myproject\\mysecurity\\mysecurity-demo\\src\\main\\java\\com\\nxz\\controller";

File localFile = new File(holder, new Date().getTime() + ".txt");

file.transferTo(localFile);

return new FileInfo(localFile.getAbsolutePath());

}

}

测试用例:

//伪造的mvc环境

@Autowired

private WebApplicationContext webApplicationContext;

private MockMvc mockMvc;

@Before

public void before() {

mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();

}

@Test

public void whenUploadSuccess() throws Exception {

String file = mockMvc.perform(MockMvcRequestBuilders.fileUpload("/file")

.file(new MockMultipartFile("file", "test.txt", "multipart/form-data", "hello".getBytes("UTF-8"))))

.andExpect(MockMvcResultMatchers.status().isOk())

.andReturn().getResponse().getContentAsString();

System.out.println(file);

}

测试用例执行完之后输出文件绝对路径:

{"path":"G:\\mysecurity\\mysecurity-demo\\src\\main\\java\\com\\nxz\\controller\\1556463660034.txt"}

下载:

@GetMapping("/{id}")

public void downLoad(@PathVariable String id,

HttpServletRequest request,

HttpServletResponse response) throws IOException {

String holder = "G:\\0001-myproject\\mysecurity\\mysecurity-demo\\src\\main\\java\\com\\nxz\\controller";

try (

InputStream inputStream = new FileInputStream(new File(holder, id + ".txt"));

OutputStream outputStream = response.getOutputStream();

) {

response.setContentType("application/x-download");

response.addHeader("Content-Disposition", "attachment;filename=test.txt");//重新定义下载后名称

//将文件输入流复制到输出刘超过年 commons-io依赖

IOUtils.copy(inputStream, outputStream);

outputStream.flush();

}

}

访问:http://localhost:8080/user/1

标签:java,springboot,mysecurity,api,file,new,import,restful,public

来源: https://www.cnblogs.com/nxzblogs/p/10787705.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值