代码实现
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
@Controller
@RequestMapping("/down/")
public class FileDownloadController {
@GetMapping("hardDisk")
public ResponseEntity hardDisk() {
File hardDiskFile = new File("/Users/itkey/Desktop/temp.mp4");
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(hardDiskFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
InputStreamResource inputStreamResource = new InputStreamResource(fileInputStream);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
httpHeaders.setContentDispositionFormData("attachment", hardDiskFile.getName());
httpHeaders.setContentLength(hardDiskFile.length());
return new ResponseEntity(inputStreamResource, httpHeaders, HttpStatus.CREATED);
}
}