前言
使用maven的时候,不像直接用ide或者自己安装的tomcat一样比较容易找到虚拟路径或者把东西上传到实体路径,我在做些项目的时候本来是打算装想装nginx,但是我的虚拟机是Ubuntu的什么依赖都没有安装好,我尝试了一天时间去安装各种东西,首先nginx它又依赖gcc-g++, gcc-g++又依赖zlib,zlib又依赖ssl,我...最后还是放弃了....(在尝试自己做创智播客视频中的淘淘商城的项目)
解决办法
既然不能使用nginx来上传我的图片,那我只能按照原来的办法去解决了,但是使用maven构建的项目并不像普通项目一样容易找到项目部署的位置,找了挺长时间的,最后才发现是安装在下面这个目录:
String path = request.getSession().getServletContext().getRealPath("/") ;
//打印出来的结果是F:\taotao\workspace-template\template\taotao-manager\taotao-manager-web\src\main\webapp
由上可知图片上传的路径可表示为request.getSession.getServletContext().getRealPah("/") + "WEB-INF/uploadedImages/",由于在配置文件中配置了
<mvc:resources location="/WEB-INF/uploadedImages/" mapping="/uploadedImages/**"></mvc:resources>//springmvc.xml中配置
那么图片的src为** http:localhost:8080/uploadedImages/**。
好吧,既然目录有了,其他事情就可以慢慢理顺了
先搭建ssm中的service层,这里我们要获得控制层传过来的MultipartFile类型的文件,这个类可以让你获得文件的类型,文件名称,文件inputstream,接口如下:
//此处我们还在在request中获得虚拟路径的文件目录地址
public interface PictureService {
public Map uploadPicture(MultipartFile multipartFile,String path);
}
PictureServiceImpl中需要做的事情是获得文件File类,然后对文件重命名,再用FileUtils的copyFile把文件拷贝到部署好的服务器中
@Service
public class PictureServiceImpl implements PictureService {
@Override
public Map uploadPicture(MultipartFile multipartFile,String path) {
Map resultMap = new HashMap<>();
//上传的方式
try {
//1.命名文件
String oldName = multipartFile.getOriginalFilename();
String newName = IDUtils.genImageName();
newName = newName + oldName.substring(oldName.lastIndexOf("."));
InputStream inputStream = multipartFile.getInputStream();
//2.把multipartFile转化为File
//2.1 临时文件 xxx.png 或者 xxx.jpg等
String temFile = "tem"+oldName.substring(oldName.lastIndexOf("."));
//2.2 生成新文件
File srcFile = new File(temFile);
//2.3 打开一个已存在文件的输出流
FileOutputStream fos = new FileOutputStream(srcFile);
//2.4 将输入流is写入文件输出流fos中
int ch = 0;
while((ch=inputStream.read()) != -1){
fos.write(ch);
}
//System.out.println(newName+"----"+temFile);
//3. 上传文件
FileUtils.copyFile(srcFile, new File(path,newName));
fos.close();
inputStream.close();
resultMap.put("url", "uploadedImages/"+newName);
resultMap.put("error", 0);
return resultMap;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
resultMap.put("message", "上传失败!");
resultMap.put("error", 1);
return resultMap;
}
}
}
里面主要包含了:
- 1.命名文件
- 2.把multipartFile转化为File
- 3.上传文件操作
Controller;里面需要配置路径给service 返回Map给前端影响
@Controller
public class PictureContrller {
@Autowired
private PictureService pictureService;
@RequestMapping("/pic/upload")
@ResponseBody
public Map pictureUpload(MultipartFile uploadFile,HttpServletRequest request){
String path = request.getSession().getServletContext().getRealPath("/") + "WEB-INF\\uploadedImages\\";
System.out.println(path);
return pictureService.uploadPicture(uploadFile,path);
}
}
上传成功后,可以在F:\taotao\workspace-template\template\taotao-manager\taotao-manager-web\src\main\webapp\WEB-INF\uploadedImages 下看到上传成功的图片