我们平时在上传图片、文件的时候都会用到form表单进行上传,但是上传之后会跳转页面。这里我用第二种方式上传:采用Ajax 异步请求的方式。
1、后端接口设计
/** * 上传文件 * @param file * @return * @throws Exception */ @RequestMapping(value = "/upload",method = RequestMethod.POST) public CommonResult upload(CommonResult commonResult, @RequestParam(value = "file",required = false) MultipartFile file) throws Exception { String fileName = ""; if (!file.isEmpty()) { BufferedOutputStream out = null; File fileSourcePath = new File(PATH); if (!fileSourcePath.exists()) { fileSourcePath.mkdirs(); } fileName = file.getOriginalFilename(); LOGGER.info("上传的文件名为:" + fileName); out = new BufferedOutputStream( new FileOutputStream(new File(fileSourcePath, fileName))); out.write(file.getBytes()); out.flush(); System.out.println(fileName.toString()); } commonResult.setCodeAndMessage(ApiStatusCode.SUCCESS,""); commonResult.setData(fileName); return commonResult; }
其中commonResult是自己定义的统一返回结果的封装。
2、前端设计
<form id = "upload" method="POST" enctype="multipart/form-data"> <input type="file" name="file" id = "pic"/> <input type="button" value="提交" id = "upload_button" /> </form>给这个button添加点击事件:
/** * 上传封面,上传成功后将图片的URl填入 * */ $("#upload_button").click(function () { var formData = new FormData($("#upload")[0]); api.uploadFile(formData).then(function (res) { if (res.code == 200) { var imageName = res.data; // var imageUrl = HOST_IMAGES + imageName; // 给封面 赋值 // $("#txt_images").val(imageUrl); } }) });Ajax 异步请求发送
/** * 上传文件 * @returns {*} */ uploadFile : function (formData) { var url = HOST_INFOGRAPHIC + "upload"; return $.ajax({ url : url, type: 'post', data : formData, //dataType:'jsonp' processData:false, contentType:false }) }以上就是前端和后端主要的代码设计了。图片已经被上传到指定的服务器的路径上面。本例中我通过Nginx服务器自己搭建一个图片服务器,这样就可以通过http请求也能访问到上传上去的图片了,这里就不说Nignx服务器的搭建了,可以参考我的这篇博客:http://blog.youkuaiyun.com/wusd1256/article/details/77772675
这里我主要说下搭建图片服务Nginx的配置。
server {
listen 80;
server_name dev.test.com;
location / {
root D:/idea-workspase/Journal/app;
index index.html;
}
location /w-api {
proxy_pass http://127.0.0.1:8088;
}
location /images/ {
root D:/idea-workspase/infographic_cms;
autoindex on;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
访问这个链接 http://dev.test.com/images/111.png 就可以访问到上传的图片111.png了。