Java用transferTo方式实现文件上传

import com.springbootemaildemo.entity.ResponseEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
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")
@Api("文件操作")
public class FileController {
    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public ResponseEntity uploadFile(@RequestParam("file") MultipartFile file) {
        long startTime = System.currentTimeMillis();
        String path = "";
        String originalFilename = file.getOriginalFilename();
        logger.info("fileName:" + originalFilename);
        int lastIndexOf = originalFilename.lastIndexOf(".");
        String fileType = originalFilename.substring(lastIndexOf + 1);
        //文件类型判断 doc,docx,jpg,png,xls
        logger.info("截取文件名类型:{}", fileType);
        if (fileType.equals("jpg") || fileType.equals("png") || fileType.equals("dox") || fileType.equals("docx") || fileType.equals("xls")) {
            path = "D:/filesss/" + new Date().getTime() + originalFilename;
            File newFile = new File(path);
            //通过CommonsMultipartFile的方法直接写文件(注意这个时候)
            try {
                file.transferTo(newFile);
                long endTime = System.currentTimeMillis();
                logger.info("采用file.Transto的运行时间:" + String.valueOf(endTime - startTime) + "ms");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            return new ResponseEntity("500", "不允许该" + fileType + "文件类型上传", "fail");
        }
        return new ResponseEntity("200", path, "success");
    }
}
Java实现文件上传下载可以使用Servlet或SpringMVC框架,这里我为您提供SpringBoot框架的代码示例。 1. 文件上传: 在SpringBoot中,我们可以使用MultipartFile类来接收上传的文件。以下是一个简单的文件上传示例: ```java @PostMapping("/upload") public String upload(@RequestParam("file") MultipartFile file) throws IOException { String fileName = file.getOriginalFilename(); String filePath = "/path/to/save/file/" + fileName; File dest = new File(filePath); file.transferTo(dest); return "success"; } ``` 其中,@PostMapping("/upload")表示接收POST请求,并映射到/upload路径;@RequestParam("file")表示接收名为"file"的文件参数,将其转化为MultipartFile类型;MultipartFile提供了transferTo方法,可以将上传的文件保存到指定的文件路径中。 2. 文件下载: 在SpringBoot中,我们可以使用ResponseEntity类来实现文件下载。以下是一个简单的文件下载示例: ```java @GetMapping("/download") public ResponseEntity<byte[]> download() throws IOException { String filePath = "/path/to/download/file/"; File file = new File(filePath); HttpHeaders headers = new HttpHeaders(); headers.setContentDispositionFormData("attachment", file.getName()); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK); } ``` 其中,@GetMapping("/download")表示接收GET请求,并映射到/download路径;HttpHeaders提供了setContentDispositionFormData方法,可以设置下载文件的名称;MediaType.APPLICATION_OCTET_STREAM表示以二进制流的形式下载文件。FileUtils.readFileToByteArray方法可以将指定文件读取为字节数组,最终使用ResponseEntity返回下载结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值