最近接到一个任务:新建一个Controller,在里面写入上传文件功能,上传后写入h2数据库,数据库有两个字段,一个是文件名,另一个是文件内容(用Blob类型存入)。
上传成功在提交按钮旁边提示成功,否则失败。
在网上也看到不少关于上传文件的教程,大体都差不多,主要还是看项目的需求了。 html代码: <body> <input type="file" name="file_upload" id="file"/><br/> <input type="button" value="上传" id="ajaxUpload"/> <span id="result" style="color:red"></span> </body> 这里没有写入submit,而是通过button按钮触发提交,提交后利用ajax提示是否上传成功: $(function() { $('#ajaxUpload').click(uploadFile); }); function uploadFile() { var data = new FormData(); var uploadfile = $('#file')[0].files[0]; data.append('file', uploadfile); var url = 'http://localhost:8080/Wts/file/uploadfile'; $.ajax({ url: url, data: data, type: 'POST', cache: false, processData: false, contentType: false }) .done(function(res) { $('#result').html('上传成功'); }) .fail(function(res) { $('#result').html('上传失败'); }); } 下面是Controller的java代码: @RequestMapping("/file") public class fileUpload { @RequestMapping("/upload") public String upload () { return “/file/upload”; } @RequestMapping("/uploadfile") public void upload(MultipartFile file, HttpServletResponse response, HttpServletRequest request) throws Exception { String fileName = file.getOriginalFilename();//获取文件名 response.setHeader("Content-Disposition", "attachment; fileName=" + new String(fileName.getBytes("GBK"), "UTF-8"));//解决文件中文名称的乱码 String path = request.getSession().getServletContext().getRealPath("upload");//上传到服务器,存到一个名为upload的文件夹里 if(file.getOriginalFilename() == null) { throw new RuntimeException("文件名不能为空"); } if(file.getOriginalFilename().length() > 128) { throw new RuntimeException("文件名过长");}
if(file.getSize() == 0) {
throw new RuntimeException("文件内容不能为空"); } if(file.getSize() > 2147483647) { throw new RuntimeException("文件过大"); } File files = new File(path, fileName); if(!files.exists()) { files.mkdirs(); } file.transferTo(files);//把file写入到服务器的files中 save(files); //保存后把上传到服务器的文件删除 files.delete(); } 插入h2数据库代码: public static void save (File files) throws Exception { Connection conn = null; try { conn = getConnection(); String sql = "INSERT INTO UPLOAD_DATA_FILE (file_name, file_data) VALUES(?, ?)"; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, files.getName()); FileInputStream fis = new FileInputStream(files);//读取服务器的文件 int len = (int) files.length(); ps.setBinaryStream(2, fis, len);//写入二进制文件 ps.executeUpdate(); fis.close();//这里一定要关闭,如果不关闭就删除不了上传到服务器的文件 } catch(SQLException e) { e.printStackTrace(); } finally { close(conn); } }