以下是一個(gè)使用 Java 編寫的示例代碼,該代碼實(shí)現(xiàn)了在網(wǎng)頁端上點(diǎn)擊上傳附件并選擇本地文件進(jìn)行上傳的接口:
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
public class FileUploadController {
@PostMapping("/upload")
public ResponseEntity uploadFile(@RequestParam("file") MultipartFile file) {
// 檢查文件是否為空
if (file.isEmpty()) {
return ResponseEntity.badRequest().body("請選擇要上傳的文件");
}
try {
// 執(zhí)行文件上傳操作
// 在這里,你可以實(shí)現(xiàn)具體的文件上傳邏輯,例如將文件保存到特定位置或?qū)⑽募鎯Φ綌?shù)據(jù)庫中
// 可以使用 file.getInputStream() 獲取文件輸入流進(jìn)行操作
return ResponseEntity.ok("文件上傳成功");
} catch (Exception e) {
return ResponseEntity.status(500).body("文件上傳失敗");
}
}
}
以上代碼使用 Spring Web 庫實(shí)現(xiàn)了一個(gè) RESTful 風(fēng)格的上傳文件接口。在這個(gè)例子中,/upload 路徑對應(yīng)上傳文件的接口。接口
標(biāo)簽: