java上傳下載檔案部署到linux系統下的一些問題
專案遇到上傳下載,在windows系統上測試都可以,但是部署到linux上就不行,試了很多種方法,只有這種才通過了。
首先上傳
/**
* 上傳
*/
@RequestMapping(value="/upload",method = RequestMethod.POST)
@ResponseBody
public String upload(@RequestParam MultipartFile myFile, HttpSession session) throws Exception{
logBefore(logger, "新增projectattach");
String realPath = "/mnt/fileserver/upload/";
//String realPath = "/G:/mnt/fileserver/resourceroot/";
// 執行上傳,FileUpload是我的工具類,見下。
String fileName = FileUpload.fileUp(myFile, realPath, System.currentTimeMillis() + ""); //這個時候檔名是時間字串,真正用來下載的檔名
String oriFileName = myFile.getOriginalFilename();//中文的檔名,用來展示的。
String realFullName = realPath + fileName;
//資料庫插入資料
PageData pd = new PageData();
pd.put("PROJECT_ATTACH_ID", this.get32UUID());//主鍵
pd.put("NAME", oriFileName);
pd.put("FILE", realFullName);
pd.put("PROJECT_ID", ProId);
ProId="";
projectAttachService.save(pd);
return "1";
}
public class FileUpload {
/**
* @param file //檔案物件
* @param filePath //上傳路徑
* @param fileName //檔名
* @return 檔名
*/
public static String fileUp(MultipartFile file, String filePath, String fileName){
String extName = ""; // 副檔名格式:
try {
if (file.getOriginalFilename().lastIndexOf(".") >= 0){
extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
}
copyFile(file.getInputStream(), filePath, fileName+extName).replaceAll("-", "");
} catch (IOException e) {
System.out.println(e);
}
return fileName+extName;
}
/**
* 寫檔案到當前目錄的upload目錄中
*
* @param in
* @param fileName
* @throws IOException
*/
private static String copyFile(InputStream in, String dir, String realName)
throws IOException {
File file = new File(dir, realName);
if (!file.exists()) {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
}
FileUtils.copyInputStreamToFile(in, file);
return realName;
}
}
然後前臺展示,只要看href那兒的寫法就可以了。
var itemId = '${pd.ITEM_ID}';
$(top.hangge());
$(function() {
getProjectAttach(itemId);
});
function getProjectAttach(itemId) {
$.ajax({
type: "POST",
url: '<%=basePath%>project/getProjectAttach.do?projectid='+itemId,
async: false,
dataType:'json',
success: function(data){
if(data != null && data !=""){debugger
$("#uploadedFilesDiv").empty();
for(var i=0;i<data.length;i++){
var dirs=new Array();
dirs=data[i].file.split("trunk");
var dir=dirs[1];
var id = '"'+data[i].projectattachid+'"';
var fileHtml = "<div style='float:left;margin:5px 15px;'>"
+ "<a href='" + 'project/download.do?fileNameEncode=' +encodeURI(encodeURI(data[i].name)) +'&realPath='+data[i].file+"'>" + data[i].name + "</a>"
+ " <span style='cursor:pointer;' onclick='removeAttach(" + id + ");' title='刪除'><i class='icon-remove' style='color:red;'></i></span>"
+"</div>";
$("#uploadedFilesDiv").append(fileHtml);
}
}
}
});
}
下載後臺:
/**
* 下載
* @throws UnsupportedEncodingException
*/
@RequestMapping(value = "/download", method = RequestMethod.GET)
public void downLoad(HttpServletRequest request, HttpServletResponse response,
String fileNameEncode, String realPath) throws UnsupportedEncodingException {
DataInputStream dis = null;
OutputStream os = null;
try {
os = response.getOutputStream();
response.setContentType("application/x-msdownload;");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-disposition", "attachment; filename*=utf-8'zh_cn'" + fileNameEncode);
dis = new DataInputStream(new FileInputStream(realPath));
byte[] buffer = new byte[204800];
int readSize = 0;
while ((readSize = dis.read(buffer)) != -1) {
os.write(buffer, 0, readSize);
}
os.flush();
dis.close();
dis = null;
} catch (IOException e) {
e.printStackTrace();
logger.error(e, e);
} finally {
try {
if (null != dis) {
dis.close();
}
if (null != os) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
logger.error(e, e);
}
}
}