我已经开始了一个简单的网站项目来学习Spring。我试图检查文件扩展名并仅在电路板上上传图像文件。所以我在上传文件之前添加了if else语句,但它看起来似乎工作正常。 我的代码如下:
@Controller
public class FileUploadController {
@RequestMapping("/write")
public String write(HttpServletRequest request, @RequestParam("bFile") MultipartFile bFile, Model model) {
System.out.println("writeDao()");
String savePath = request.getSession().getServletContext().getRealPath("/fileUpload");
String originalFName = bFile.getOriginalFilename();
String onlyFName = originalFName.substring(0, originalFName.indexOf("."));
String extension = originalFName.substring(originalFName.indexOf(".")); // .jpg
String rename = onlyFName + "_" + getCurrentDayTime() + extension; // fileName_20150721-14-07-50.jpg
String fullPath = savePath + "\\" + rename;
if(!bFile.getContentType().equals("images/jpeg")) {
try{
byte[] bytes = bFile.getBytes();
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(fullPath)));
stream.write(bytes);
stream.close();
System.out.println("Success to upload file");
} catch (Exception e) {
System.out.println("Fail to upload file");
}
} else {
System.out.println("Choose file to upload");
}
String bPwd = request.getParameter("bPwd");
BoardDao dao = sqlSession.getMapper(BoardDao.class);
dao.writeDao(pwd, rename, fullPath);
return "redirect:list";
}
//file upload.jsp
<form action="write" method="post" enctype="multipart/form-data">
<tr>
<td> File </td>
<td> <input type="file" multiple accept='image/*' name="bFile" size = "50"> </td>
</tr>
</form>