@RequestMapping(value = "/mi/upload", method = RequestMethod.POST)
@ResponseBody
public MyResponse upload(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
long size = file.getSize();
if(size>1024*1024*2){
throw new MyException("图片大小不能超过2M");
}
String classpath = this.getClass().getResource("/").getPath().replaceFirst("/", "");
//String webappRoot = classpath.replaceAll("WEB-INF/classes/", "");
//可以自定义路径
File dir = new File(classpath+"/images");
if(!dir.isDirectory()){
dir.mkdirs();
}
String accessUrl = "/images/"+System.currentTimeMillis()+file.getName()+".jpg";
try {
File file1 = new File(classpath+accessUrl);
file.transferTo(file1);
} catch (IOException e) {
e.printStackTrace();
throw new MyException("上传失败");
}
}
2.读取本地文件内容
// String filepath = "E:/upload/test.txt";//E盘下的文件夹的目录
// File targetFile = new File(filepath);//File类型可以是文件也可以是文件夹
//
// // File targetFile = new File(path);
// if (!targetFile.exists()) {
// targetFile.mkdirs();
// }
// //保存到本地的文件
// // File saveFile = new File(path + fileName);
// FileInputStream fileInput = null;
// String rs = "";
// try {
// // 通过File对象构建一个流对象
// fileInput = new FileInputStream(targetFile);
// // 读取数据,并将读取的数据存储在数组中
// byte[] data = new byte[(int) targetFile.length()];
// // 读取流中的第一个字节数据
// int n = fileInput.read();
// // 读取的游标位置
// int i = 0;
// // 判断是否读到最后一个字符
// while (n != -1) {
// data[i] = (byte) n;
// i++;
// n = fileInput.read();
// }
// rs = new String(data, "GBK");
// System.out.println(rs);
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
// try {
// file.transferTo(targetFile);
// return new MyResponse(rs);
// } catch (Exception e) {
// e.printStackTrace();
// return new MyResponse(ResponseCode.OPERATE_FAIL, e.getMessage());
// }