文件上传——选择文件之后自动上传||文件上传的后端代码
程序员文章站
2022-06-02 23:29:19
...
选择文件之后自动上传
//普通图片上传
var uploadInst = upload.render({
elem: '#test1'
, url: 'file/upload.action'
, accept: 'images'
, acceptMime: 'image/*'
, auto: true//是否选择文件之后自动上传
, field: 'mf' //表单的name值
, before: function (obj) {
//预读本地文件示例,不支持ie8
obj.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 () {
//演示失败状态,并实现重传
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();
});
}
});
非自动上传
<!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>常规使用:普通图片上传</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>选完文件后不自动上传</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">开始上传</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//是否选择文件之后自动上传
, field: 'mf' //表单的name值
, before: function (obj) {
//预读本地文件示例,不支持ie8
obj.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 () {
//演示失败状态,并实现重传
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();
});
}
});
//不自动上传
upload.render({
elem: '#test8',
url: 'file/upload.action',
field: 'mf',
accept: 'images',
acceptMime: 'image/*',
auto: false, //去掉自动上传
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("服务器异常");
}
})
});
</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;
/**
* 随机工具类
*/
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();
/**
* 得到当前日期
*/
public static String getCurrentDateForString() {
return sdf1.format(new Date());
}
/**
* 生成文件名使用时间+4位随机数
* @param suffix 文件名称
*/
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 文件名称
*/
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,使用绝对路径+相对路径去找到文件对象
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转成一个bytes
byte [] bytes=FileUtils.readFileToByteArray(file);
HttpHeaders header=new HttpHeaders();
//封装响应内容类型(APPLICATION_OCTET_STREAM 响应的内容不限定)
header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//设置下载的文件的名称
header.setContentDispositionFormData("attachment", oldName);
//创建ResponseEntity对象
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 block
e.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 {
/**
* 文件上传
* 上传一个文件保存到E://upload
* @throws IOException
*/
@RequestMapping("upload")
@ResponseBody
public Map<String,Object> upload03(MultipartFile mf) throws IOException {
System.out.println(mf);
System.out.println(mf.getContentType());//文件的类型
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;
//得到当前日期作为文件夹名称
String dirName=RandomUtils.getCurrentDateForString();
//构造文件夹对象
File dirFile=new File(parentPath,dirName);
if(!dirFile.exists()) {
dirFile.mkdirs();//创建文件夹
}
//得到文件原名
String oldName=mf.getOriginalFilename();
//根据文件原名得到新名
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, "");
}
}
下一篇: 微信公众平台使用说明