<script src="jquery-1.9.0.js"></script>
<script src="jquery.form.js"></script> <!-- 關鍵插件 -->
<form id="uploadImgForm" action="${ctx}/upload/upload.do" method="post" enctype="multipart/form-data">
<div class="control-group">
<label class="control-label">*商圈名:</label>
<div class="controls">
<input type="text" name="businessName" maxlength="20" id="businessName" />
<input type="hidden" name="userId" value="${userId}" />
</div>
</div>
<div class="control-group">
<label class="control-label">*商圈 Logo:</label>
<div class="controls">
<input type="file" name="file" id="file" />
</div>
</div>
<div class="control-group">
<label class="control-label">*商圈英文名:</label>
<div class="controls">
<input type="text" name="businessEname" id="businessEname" />
</div>
</div>
<div class="form-actions">
<button type="button" id="imgSave" class="btn btn-primary">提交註冊</button>
</div>
</form>
$(document).ready(function() {
// 即時驗證
$('#businessName, #businessEname').blur(function() {
var $this = $(this), $err = $('#' + this.id + '_error');
if ($this.val()) $err.html("<img src='success.gif'>");
else $err.addClass('error_div').html("<img src='error.gif'> 不能為空");
});
// 提交
$('#imgSave').click(function() {
// 前端驗證
var ok = true;
$('#businessName, #businessEname, #file').each(function() {
if (!$(this).val()) {
$('#' + this.id + '_error').addClass('error_div').html("<img src='error.gif'> 必填");
ok = false;
}
});
if (!ok) return;
// 檢查副檔名
var ext = $('#file').val().split('.').pop().toLowerCase();
if (!['jpg','jpeg','gif','bmp','png'].includes(ext)) {
$('#file_error').addClass('error_div').html("<img src='error.gif'> 格式不支援");
return;
}
// ajaxSubmit 核心
$('#uploadImgForm').ajaxSubmit({
type: 'POST',
dataType: 'json',
beforeSubmit: function() {
$('#imgSave').prop('disabled', true).text('上傳中...');
},
success: function(result) {
if (result.success) {
alert('註冊成功!');
location.href = '${ctx}/business/list';
} else {
alert('失敗: ' + result.msg);
}
},
error: function(xhr) {
alert('系統錯誤: ' + xhr.status);
},
complete: function() {
$('#imgSave').prop('disabled', false).text('提交註冊');
}
});
});
});
@Controller
@RequestMapping("/upload")
public class UploadController {
@PostMapping("/upload.do")
@ResponseBody
public Map upload(
@RequestParam("businessName") String businessName,
@RequestParam("businessEname") String businessEname,
@RequestParam("userId") Long userId,
@RequestParam("file") MultipartFile file) {
Map result = new HashMap<>();
try {
// 1. 驗證檔案
if (file.isEmpty()) { result.put("success", false); result.put("msg", "檔案為空"); return result; }
// 2. 儲存檔案 (生成唯一檔名、驗證 MIME、掃毒...)
String original = file.getOriginalFilename();
String ext = FilenameUtils.getExtension(original).toLowerCase();
String newName = UUID.randomUUID() + "." + ext;
Path dest = Paths.get(uploadDir, newName);
Files.copy(file.getInputStream(), dest);
// 3. 存入資料庫
Business biz = new Business();
biz.setName(businessName);
biz.setEname(businessEname);
biz.setLogoUrl("/uploads/" + newName);
biz.setUserId(userId);
businessService.save(biz);
result.put("success", true);
} catch (Exception e) {
log.error("上傳失敗", e);
result.put("success", false); result.put("msg", "伺服器錯誤");
}
return result;
}
}
| 關鍵點 | 說明 |
|---|---|
enctype="multipart/form-data" | 表單必須設定,否則檔案不會上傳 |
jquery.form.js | 自動將 FormData 序列化並處理 iframe/ XHR2 相容 |
ajaxSubmit() | 一鍵提交表單含檔案,支援進度事件 uploadProgress |
| 前端驗證 | 必填、副檔名、檔案大小 (可用 file.size HTML5 File API) |
| 後端 MultipartResolver | Spring 需配置 CommonsMultipartResolver 或 StandardServletMultipartResolver |
| 安全性 | 檔案類型驗證 (MIME + 副檔名)、重新命名、存儲路徑非 Web 可直接訪問、病毒掃描 |
document.getElementById('imgSave').addEventListener('click', async () => {
const form = document.getElementById('uploadImgForm');
const formData = new FormData(form); // 自動收集所有欄位含檔案
// 可追加額外欄位
// formData.append('extra', 'value');
const btn = this;
btn.disabled = true; btn.textContent = '上傳中...';
try {
const resp = await fetch(form.action, { method: 'POST', body: formData, credentials: 'include' });
const result = await resp.json();
if (result.success) { alert('成功'); location.href = '${ctx}/business/list'; }
else alert('失敗: ' + result.msg);
} catch (e) { alert('異常: ' + e); }
finally { btn.disabled = false; btn.textContent = '提交註冊'; }
});
零依賴、原生支援進度事件 (xhr.upload.onprogress)、程式碼更簡潔。