前言
使用maven的時候,不像直接用ide或者自己安裝的tomcat一樣比較容易找到虛擬路徑或者把東西上傳到實(shí)體路徑,我在做些項(xiàng)目的時候本來是打算裝想裝nginx,但是我的虛擬機(jī)是Ubuntu的什么依賴都沒有安裝好,我嘗試了一天時間去安裝各種東西,首先nginx它又依賴gcc-g++, gcc-g++又依賴zlib,zlib又依賴ssl,我...最后還是放棄了....(在嘗試自己做創(chuàng)智播客視頻中的淘淘商城的項(xiàng)目)
解決辦法
既然不能使用nginx來上傳我的圖片,那我只能按照原來的辦法去解決了,但是使用maven構(gòu)建的項(xiàng)目并不像普通項(xiàng)目一樣容易找到項(xiàng)目部署的位置,找了挺長時間的,最后才發(fā)現(xiàn)是安裝在下面這個目錄:
String path = request.getSession().getServletContext().getRealPath("/") ;
//打印出來的結(jié)果是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把文件拷貝到部署好的服務(wù)器中
@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轉(zhuǎn)化為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轉(zhuǎn)化為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 下看到上傳成功的圖片