最近在做一个文件上传的功能,也是比较简单,这里算是记录一下吧
其实我们最好能区分只是单纯的上传图片还是其他文件,这里记录一个可以传各种格式文件的和一个特定图片格式的
工具类:
public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception { File targetFile = new File(filePath); if (!targetFile.exists()) { targetFile.mkdirs(); } //如果文件存在就先删除了 File ifFile = new File(filePath + File.separator + fileName); if (ifFile.exists()) { logger.debug("File is exists!"); ifFile.delete(); } //然后再写文件 FileOutputStream out = null; try { out = new FileOutputStream(filePath + File.separator + fileName); out.write(file); } catch (Exception e) { logger.error("Error:", e); } finally { if (out != null) { out.close(); } } }Postman测试: 服务器看到的:
这个思路就是前端先把图片用base64读取压缩成字符串,然后再把字符串写入成图片
//image就是base64的字符串格式 byte[] imageByte = Base64Helper.decode(image); File file = new File(filepath + filename); RandomAccessFile randomAccessFile = null; try{ randomAccessFile=new RandomAccessFile(file,"rw"); randomAccessFile.seek(0); try{ randomAccessFile.write(imageByte); }catch(UnsupportedEncodingException e){ logger.error("Error:",e); } }catch(IOException e){ logger.error("Error:",e); throw e; }finally{ if(randomAccessFile!=null){ try{ randomAccessFile.close(); }catch(IOException e){ logger.error("Error:",e); } } }