1.首先引入jar包
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency>
2.前端代码
<input id="img" type="file" onchange="sendChange();"/> <script> function sendChange() { fileUpload(); } function fileUpload() { var formData = new FormData(); formData.append('img', $('#img')[0].files[0]); if (!validate_img($('#img'))) { return; } $.ajax({ url: '/upload', type: 'POST', cache: false, data: formData, processData: false, contentType: false, beforeSend: function() { }, success: function(data) { alert(data.url); if (data.code == 1) { alert('上传成功'); } }, error: function() { } }); } //限制上传文件的类型和大小 function validate_img(ele) { // 返回 KB,保留小数点后两位 var file = ele.val(); if (!/.(gif|jpg|jpeg|png|GIF|JPG|bmp)$/.test(file)) { alert("图片类型必须是.gif,jpeg,jpg,png,bmp中的一种"); return false; } else { //返回Byte(B),保留小数点后两位 if (((ele[0].files[0].size).toFixed(2)) >= (10 * 1024 * 1024)) { alert("请上传小于10M的图片"); return false; } else return true; } return false; } </script>
3.服务端控制器代码
package webapp.controller; import com.alibaba.fastjson.JSONObject; import org.apache.commons.io.FileUtils; import org.springframework.context.annotation.Scope; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.util.UUID; @Scope("prototype") @RestController public class FileController { @RequestMapping("upload") @ResponseBody public JSONObject upload(@RequestParam("img") MultipartFile file) { JSONObject out = new JSONObject(); if (file.isEmpty()) { return null; } String filePath = "/Users/xxx";//文件路径 File dir = new File(filePath); if(! dir.exists()) { dir.mkdir(); } String orgName = file.getOriginalFilename(); String[] split = orgName.split("\."); String suffix = split[1]; String path = filePath + UUID.randomUUID() +"."+suffix; File tempFile = null; try { tempFile = new File(path); FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile); } catch (IllegalStateException e) { out.put("code",0); } catch (IOException e) { out.put("code",0); } out.put("code",1); out.put("url",path); return out; } }
完事儿~