所需依赖:
代码:
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import io.swagger.annotations.ApiOperation;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
@RestController
public class TXTConversionController {
@ApiOperation("文件转换,txt转docx")
@RequestMapping("/uploadTXTConvert")
public ResponseEntity<ByteArrayResource> convertTXTDocx(@RequestParam("file") MultipartFile uploadedFile) throws IOException {
if (uploadedFile.isEmpty()) {
return ResponseEntity.badRequest().build();
}
String originalFileName = uploadedFile.getOriginalFilename();
// 检查文件扩展名,确保上传的文件是DOC格式
if (!originalFileName.toLowerCase().endsWith(".txt")) {
return ResponseEntity.badRequest().body(new ByteArrayResource(new byte[0]));
}
//读取上传的DOC文件
InputStream docInputStream = uploadedFile.getInputStream();
Document document = new Document(docInputStream);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
document.saveToStream(outputStream, FileFormat.Docx);
byte[] docxBytes = outputStream.toByteArray();
ByteArrayResource resource = new ByteArrayResource(docxBytes);
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=converted.docx");
return ResponseEntity.ok()
.headers(headers)
.contentLength(docxBytes.length)
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
}
}