记录以后可能会用到。
首先前端代码:
<div class="uploadbox">
<input type="file" id="file" style="display:none" onChange="up()">
<button type="button" class="" id="test1" onclick="file.click()">
<i class="layui-icon"></i>上传文件</button>
</div>
//上传文档 具体实现
function up(){
var max=4*1024*1024;//4194304
$("#loading2").show();
var file = $("#file")[0].files[0]; //取值
if(file && file.size>max){
$("#loading2").hide(); //只是loading图可忽略
alert("上传文件不能超过4M,请重新上传");
return false;
}
var fd = new FormData();
if (typeof(file) == "undefined") { //判断 可忽略
alert("请添加文件");
return false;
}
var point = file.name.lastIndexOf(".");
var type = file.name.substr(point+1); //文件后缀名
fd.append("file", file); //添加参数
fd.append("fileType", type);//添加参数
$("#loading").show();
$.ajax({
type: 'post',
url: "http://"+IP+"/app/document/doUploadDocuments.do",
data: fd,
method:"post",xhrFields: {withCredentials: true},crossDomain: true, //跨域操作,可忽略
cache: false,
processData: false, //这些不能忽略
contentType: false,
}).success(function (data) {
fNmame=data.msg;
$("#loading2").hide();
if(fNmame=="-1"){
alert("上传失败");
$("#file")[0].value="";//清空file的值 让他是个全新的fil以触发第二次的上传操作,不然上传相同的文件会不触发此方法
return false;
}
if(fNmame=="-2"){
alert("尚未分配服务,请申请");
$("#file")[0].value="";//清空file的值 让他是个全新的file以触发第二次的上传操作
return false;
}
}).error(function () {
$("#loading2").hide();
alert("上传失败");
});
}
下面是JAVA后端的代码与配置
我用的SpringMVC 所以在mvc配置下加了这段
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8" />
<!-- 指定所上传文件的总大小不能超过200KB,下面是字节。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
<property name="maxUploadSize" value="204800"/>
<!-- 指定上传文件的临时路径 -->
</bean>
/**
* 上传文档
* @param url
* @param entity
* @param request 注意file 与前段name同名
* @return
*/
@RequestMapping("doUploadDocuments.do")
public Message doUploadDocuments(MultipartFile file,Document entity,HttpServletRequest request) {
String uuid=null;
double originalFilesize = request.getContentLength();//获取源文件大小
InputStream in;
try {
in=file.getInputStream(); //流 拿到流就好办了。直接写文件也好,干什么都行。
entity.setFileSize((int)originalFilesize);//文件大小
uuid = app.upload(in,entity,getCurrentUser(), request); //这是跟业务有关的逻辑可忽略
in.close();
} catch (Exception e) {
}
if(uuid.equals("-1")) {
buildResultError("转换出现错误", "-1");
}
if(uuid.equals("-2")){
buildResultError("尚未分配服务,请申请", "-2");
}
return buildSuccess(uuid);
}
好了。