文件上传——选择文件之后自动上传||文件上传的后端代码
生活随笔
收集整理的這篇文章主要介紹了
文件上传——选择文件之后自动上传||文件上传的后端代码
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
選擇文件之后自動(dòng)上傳
//普通圖片上傳var uploadInst = upload.render({elem: '#test1', url: 'file/upload.action', accept: 'images', acceptMime: 'image/*', auto: true//是否選擇文件之后自動(dòng)上傳, field: 'mf' //表單的name值, before: function (obj) {//預(yù)讀本地文件示例,不支持ie8obj.preview(function (index, file, result) {$('#demo1').attr('src', result); //圖片鏈接(base64)});}, done: function (res) {alert(res);//如果上傳失敗if (res.code > 0) {return layer.msg('上傳失敗');}//上傳成功layer.msg("上傳成功");}, error: function () {//演示失敗狀態(tài),并實(shí)現(xiàn)重傳var demoText = $('#demoText');demoText.html('<span style="color: #FF5722;">上傳失敗</span> <a class="layui-btn layui-btn-xs demo-reload">重試</a>');demoText.find('.demo-reload').on('click', function () {uploadInst.upload();});}});非自動(dòng)上傳
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>文件上傳</title><link rel="stylesheet" href="resources/layui/css/layui.css"> </head> <body> <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;"><legend>常規(guī)使用:普通圖片上傳</legend> </fieldset> <div class="layui-upload"><button type="button" class="layui-btn" id="test1">上傳圖片</button><div class="layui-upload-list"><img class="layui-upload-img" width="60" height="60" id="demo1"><p id="demoText"></p></div> </div><fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;"><legend>選完文件后不自動(dòng)上傳</legend> </fieldset> <div class="layui-upload"><button type="button" class="layui-btn layui-btn-normal" id="test8">選擇文件</button><button type="button" class="layui-btn" id="test9">開(kāi)始上傳</button><br><img alt="" src="" id="myimage"> </div><script src="resources/layui/layui.js"></script> <script type="text/javascript">layui.use(['jquery', 'layer', 'form', 'table', 'laydate', 'upload'], function () {var $ = layui.jquery;var layer = layui.layer;var form = layui.form;var table = layui.table;var laydate = layui.laydate;var upload = layui.upload;//普通圖片上傳var uploadInst = upload.render({elem: '#test1', url: 'file/upload.action', accept: 'images', acceptMime: 'image/*', auto: true//是否選擇文件之后自動(dòng)上傳, field: 'mf' //表單的name值, before: function (obj) {//預(yù)讀本地文件示例,不支持ie8obj.preview(function (index, file, result) {$('#demo1').attr('src', result); //圖片鏈接(base64)});}, done: function (res) {alert(res);//如果上傳失敗if (res.code > 0) {return layer.msg('上傳失敗');}//上傳成功layer.msg("上傳成功");}, error: function () {//演示失敗狀態(tài),并實(shí)現(xiàn)重傳var demoText = $('#demoText');demoText.html('<span style="color: #FF5722;">上傳失敗</span> <a class="layui-btn layui-btn-xs demo-reload">重試</a>');demoText.find('.demo-reload').on('click', function () {uploadInst.upload();});}});//不自動(dòng)上傳upload.render({elem: '#test8',url: 'file/upload.action',field: 'mf',accept: 'images',acceptMime: 'image/*',auto: false, //去掉自動(dòng)上傳bindAction: '#test9',done: function (res) {if (res.code > 0) {return layer.msg('上傳失敗');} else {//上傳成功layer.msg("上傳成功");layer.msg(res.data.src);$("#myimage").attr("src", res.data.src);}},error: function () {layer.msg("服務(wù)器異常");}})}); </script> </body> </html>
文件上傳的后端代碼
RandomUtils.java
package com.sxt.utils;import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; import java.util.UUID;/*** 隨機(jī)工具類(lèi)*/ public class RandomUtils {private static SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd");private static SimpleDateFormat sdf2=new SimpleDateFormat("yyyyMMddHHmmssSSS");private static Random random=new Random();/*** 得到當(dāng)前日期*/public static String getCurrentDateForString() {return sdf1.format(new Date());}/*** 生成文件名使用時(shí)間+4位隨機(jī)數(shù)* @param suffix 文件名稱(chēng)*/public static String createFileNameUseTime(String fileName) {String fileSuffix=fileName.substring(fileName.lastIndexOf("."),fileName.length());String time=sdf2.format(new Date());Integer num=random.nextInt(9000)+1000;return time+num+fileSuffix;}/*** 生成文件名使用UUID* @param suffix 文件名稱(chēng)*/public static String createFileNameUseUUID(String fileName) {String fileSuffix=fileName.substring(fileName.lastIndexOf("."),fileName.length());return UUID.randomUUID().toString().replace("-", "").toUpperCase()+fileSuffix;}public static void main(String[] args) {System.out.println(createFileNameUseUUID("fasdfasdfsda,a,ff.d,sfmslafsa.gif"));} }AppFileUtils.java
package com.sxt.utils;import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.net.URLEncoder; import java.util.Properties;import javax.servlet.http.HttpServletResponse;import org.apache.commons.io.FileUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity;public class AppFileUtils {/*** 得到文件上傳的路徑*/public static String PATH;static {InputStream stream = AppFileUtils.class.getClassLoader().getResourceAsStream("file.properties");Properties properties=new Properties();try {properties.load(stream);PATH=properties.getProperty("path");} catch (IOException e) {e.printStackTrace();}}/*** 文件下載*/public static ResponseEntity<Object> downloadFile(HttpServletResponse response, String path, String oldName) {//4,使用絕對(duì)路徑+相對(duì)路徑去找到文件對(duì)象File file=new File(AppFileUtils.PATH,path);//5,判斷文件是否存在if(file.exists()) {try {try {//如果名字有中文 要處理編碼oldName=URLEncoder.encode(oldName, "UTF-8");} catch (Exception e) {e.printStackTrace();}//把file轉(zhuǎn)成一個(gè)bytesbyte [] bytes=FileUtils.readFileToByteArray(file);HttpHeaders header=new HttpHeaders();//封裝響應(yīng)內(nèi)容類(lèi)型(APPLICATION_OCTET_STREAM 響應(yīng)的內(nèi)容不限定)header.setContentType(MediaType.APPLICATION_OCTET_STREAM);//設(shè)置下載的文件的名稱(chēng)header.setContentDispositionFormData("attachment", oldName);//創(chuàng)建ResponseEntity對(duì)象ResponseEntity<Object> entity=new ResponseEntity<Object>(bytes, header, HttpStatus.CREATED);return entity;} catch (Exception e) {e.printStackTrace();}return null;}else {PrintWriter out;try {out = response.getWriter();out.write("文件不存在");out.flush();out.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}} }FileController.java
package com.sxt.controller;import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map;import javax.servlet.http.HttpServletResponse;import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile;import com.sxt.utils.AppFileUtils; import com.sxt.utils.RandomUtils;@Controller @RequestMapping("file") public class FileController {/*** 文件上傳* 上傳一個(gè)文件保存到E://upload* @throws IOException */@RequestMapping("upload")@ResponseBodypublic Map<String,Object> upload03(MultipartFile mf) throws IOException {System.out.println(mf);System.out.println(mf.getContentType());//文件的類(lèi)型System.out.println(mf.getName());//表單的name屬性值System.out.println(mf.getOriginalFilename());//文件名System.out.println(mf.getSize());//文件大小System.out.println(mf.getInputStream());//文件流//文件上傳的父目錄String parentPath=AppFileUtils.PATH;//得到當(dāng)前日期作為文件夾名稱(chēng)String dirName=RandomUtils.getCurrentDateForString();//構(gòu)造文件夾對(duì)象File dirFile=new File(parentPath,dirName);if(!dirFile.exists()) {dirFile.mkdirs();//創(chuàng)建文件夾}//得到文件原名String oldName=mf.getOriginalFilename();//根據(jù)文件原名得到新名String newName=RandomUtils.createFileNameUseTime(oldName);File dest=new File(dirFile,newName);mf.transferTo(dest);Map<String,Object> map=new HashMap<>();map.put("code", 0);map.put("msg", "");Map<String,Object> data=new HashMap<>();data.put("src", "file/downloadFile.action?path="+dirName+"/"+newName);map.put("data", data);return map;}/*** 下載的方法*/@RequestMapping("downloadFile")public ResponseEntity<Object> downloadFile(String path,HttpServletResponse response){//3,拿到文件的老名字return AppFileUtils.downloadFile(response, path, "");}}?
?
總結(jié)
以上是生活随笔為你收集整理的文件上传——选择文件之后自动上传||文件上传的后端代码的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 数据表格+弹出层的综合案例
- 下一篇: 内嵌WEB服务器加载原理