import com.example.tanwu.service.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@RestController
@RequestMapping("/api/files")
public class FileController {
@Autowired
private FileStorageService fileStorageService;
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
String fileName = fileStorageService.storeFile(file);
return ResponseEntity.status(HttpStatus.OK).body(fileName);
}
@GetMapping("/{fileName}")
public void downloadFile(@PathVariable String fileName, HttpServletResponse response) throws IOException {
InputStream inputStream = fileStorageService.loadFile(fileName);
OutputStream outputStream = response.getOutputStream();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
}
}
import com.example.tanwu.service.FileStorageService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@Service
public class FileStorageServiceImpl implements FileStorageService {
private static final String UPLOAD_DIR = "./uploads/";
@PostConstruct
public void init() {
File uploadDir = new File(UPLOAD_DIR);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
}
@Override
public String storeFile(MultipartFile file) {
try {
String fileName = file.getOriginalFilename();
File destFile = new File(UPLOAD_DIR + fileName);
OutputStream outputStream = new FileOutputStream(destFile);
InputStream inputStream = file.getInputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
return fileName;
} catch (IOException e) {
throw new RuntimeException("Failed to store file", e);
}
}
@Override
public InputStream loadFile(String fileName) {
try {
return new FileInputStream(new File(UPLOAD_DIR + fileName));
} catch (IOException e) {
throw new RuntimeException("Failed to load file", e);
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/161168.html