1.前臺上傳:html
<input type="file" name="file" id="file">
2.後臺的接收與處理:java
String uuid = UUID.randomUUID().toString(); //取得文件 MultipartFile file = form.getFile(); //獲取存放文件的路徑 File fileDir = UploadUtils.getImgDirFile(); try { //構建新文件,包含路徑+文件名 File newFile = new File(fileDir.getAbsolutePath(), uuid); //保存文件 file.transferTo(newFile); } catch (IOException e) { e.printStackTrace(); }
這裏放一下我上面構建存放文件路徑的工具類 UploadUtils :web
public class UploadUtils { /* // 項目根路徑下的目錄 -- SpringBoot static 目錄至關因而根路徑下(SpringBoot 默認) public final static String IMG_PATH_PREFIX = "static/upload/imgs";*/ public static File getImgDirFile(){ // 構建上傳文件的存放 "文件夾" 路徑 String fileDirPath = new String("C:\\webImg"); File fileDir = new File(fileDirPath); if(!fileDir.exists()){ // 遞歸生成文件夾 fileDir.mkdirs(); } return fileDir; } }
保存圖片後的文件夾:bootstrap
3.作完保存,接下來就得讓它在前臺顯示出來,這裏使用的容器是bootstrap-table,代碼以下:app
<table id="gamesTable" data-bind="bootstrapTable:$root" style="table-layout: fixed;"> <thead> <tr> <th data-checkbox="true"></th> <th data-field="img" data-formatter="showImg">概念圖</th> <th data-field="name">名稱</th> <th data-field="dev">開發商</th> <th data-field="shelfTime">發行日期</th> <th data-field="price">價格</th> </tr> </thead> </table>
JS處理data-formatter:dom
function showImg(value){ var html="<img src='games/dw?uuid="+value+"' width='100%' />"; return html; }
後臺的下載方法:工具
public void dw(String uuid,HttpServletRequest request, HttpServletResponse response) { Games fileentity = dao.findByImg(uuid); if(fileentity==null) { }else { //文件名稱 String filename = "sss.jpg"; filename = getStr(request, filename); //下載文件的路徑(即保存文件的路徑 String filePath="C:\\webImg"; File file = new File(filePath, uuid); if(file.exists()) { FileInputStream fis; try { fis = new FileInputStream(file); response.setContentType("application/x-msdownload"); response.addHeader("Content-Disposition", "attachment; filename=" + filename ); ServletOutputStream out = response.getOutputStream(); byte[] buf=new byte[2048]; int n=0; while((n=fis.read(buf))!=-1){ out.write(buf, 0, n); } fis.close(); out.flush(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } }
附上處理文件名亂碼的方法:ui
//處理文件名亂碼的問題 private String getStr(HttpServletRequest request, String fileName) { String downloadFileName = null; //僅提供了部分代碼,由於咱們已經明確問題的所在,知道修改那一部分了,(代碼中downloadFileName 即表明 *=utf-8'zh_cn'文件名.xx部分) String agent = request.getHeader("USER-AGENT"); try { if(agent != null && agent.toLowerCase().indexOf("firefox") > 0){ //downloadFileName = "=?UTF-8?B?" + (new String(Base64Utils.encode(fileName.getBytes("UTF-8")))) + "?="; //設置字符集 downloadFileName = "=?UTF-8?B?" + Base64Utils.encodeToString(fileName.getBytes("UTF-8")) + "?="; }else{ downloadFileName = java.net.URLEncoder.encode(fileName, "UTF-8"); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return downloadFileName; }
以上。spa