使用 Uploadify 前端上傳插件時,後端需提供一個接收檔案的端點,並回傳 JSON 格式的結果供前端判斷是否成功。以下以 Spring MVC 為例說明關鍵實作步驟:
@PostMapping("/upload")
@ResponseBody
public Map upload(@RequestParam("file") MultipartFile file,
HttpServletRequest request) {
Map result = new HashMap<>();
// 業務邏輯...
return result;
}
if (file.isEmpty())。/var/upload/),並確保應用程式有寫入權限。file.transferTo(new File(destPath))。result.put("success", true); result.put("msg", "上傳成功");。@PostMapping("/upload")
@ResponseBody
public Map upload(@RequestParam("file") MultipartFile file) {
Map result = new HashMap<>();
if (file.isEmpty()) {
result.put("success", false);
result.put("msg", "檔案為空");
return result;
}
String uploadDir = "/var/upload/";
File dir = new File(uploadDir);
if (!dir.exists()) dir.mkdirs();
String originalName = file.getOriginalFilename();
String ext = originalName.substring(originalName.lastIndexOf("."));
String newName = UUID.randomUUID().toString() + ext;
File dest = new File(uploadDir + newName);
try {
file.transferTo(dest);
result.put("success", true);
result.put("msg", "上傳成功");
result.put("filePath", "/upload/" + newName); // 供前端預覽或下載
} catch (IOException e) {
result.put("success", false);
result.put("msg", "上傳失敗:" + e.getMessage());
}
return result;
}
$('#file_upload').uploadify({
'swf' : '/js/uploadify.swf',
'uploader' : '/upload',
'buttonText': '選擇檔案',
'fileTypeDesc': '所有檔案',
'fileTypeExts': '*.*',
'onUploadSuccess' : function(file, data, response) {
var json = JSON.parse(data);
if (json.success) {
alert(json.msg); // 顯示「上傳成功」
} else {
alert("錯誤:" + json.msg);
}
}
});
更多完整專案原始碼可參考 xlongwei uploadify 範例,其中包含 UploadController 等可直接套用的類別。