前端代码:
<form id= "uploadform">
<p >指定文件名: <input type="text" name="filename" value= ""/></p >
<p >上传文件: <input type="file" name="file"/></ p>
<input type="button" value="上传" onclick="doupload()" />
</form>
function doupload() {
var formdata = new formdata($( "#uploadform" )[0]);
$.ajax({
url: 'http://localhost:8080/xiaochangwei/file/upload' ,
type: 'post',
data: formdata,
async: false,
cache: false,
contenttype: false,
processdata: false,
success: function (returndata) {
alert(returndata);
},
error: function (returndata) {
alert(returndata);
}
});
}
后端:
@requestmapping(value = "/upload", method = requestmethod.post)
public string upload(httpservletrequest request, @requestparam("file") multipartfile file, modelmap model) {
system.out.println("开始");
string path = request.getsession().getservletcontext().getrealpath("upload");
string filename = file.getoriginalfilename();
// string filename = new date().gettime()+".jpg";
system.out.println(path);
file targetfile = new file(path, filename);
if (!targetfile.exists()) {
targetfile.mkdirs();
}
// 保存
try {
file.transferto(targetfile);
} catch (exception e) {
e.printstacktrace();
}
model.addattribute("fileurl", request.getcontextpath() + "/upload/" + filename);
return "result";
}
如果前端有很多实体类数据同文件一同提交
可以修改后端方法为:
upload(httpservletrequest request, @requestparam("file") multipartfile file, modelmap model,user user)
利用下面的代码更可实现带有进度条的文件上传
<script type="text/javascript">
function upladfile() {
var fileobj = document.getelementbyid("file").files[0]; // js 获取文件对象
var filecontroller = "http://localhost:8080/xiaochangwei/file/upload"; // 接收上传文件的后台地址
// formdata 对象
var form = new formdata($( "#uploadform" )[0]);
// xmlhttprequest 对象
var xhr = new xmlhttprequest();
xhr.open("post", filecontroller, true);
xhr.onload = function () {
// alert("上传完成!");
};
xhr.upload.addeventlistener("progress", progressfunction, false);
xhr.send(form);
}
function progressfunction(evt) {
var progressbar = document.getelementbyid("progressbar");
var percentagediv = document.getelementbyid("percentage");
if (evt.lengthcomputable) {
progressbar.max = evt.total;
progressbar.value = evt.loaded;
percentagediv.innerhtml = math.round(evt.loaded / evt.total * 100) + "%";
if(evt.loaded==evt.total){
alert("上传完成100%");
}
}
}
</script>
<progress id="progressbar" value="0" max="100"></progress>
<form id= "uploadform">
<input type="file" id="file" name="myfile" />
<input type="button" onclick="upladfile()" value="上传" />
</form>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。