当我们需要上传一个图片或者附件时,我们必须现在前台页面获取得到该图片或者附件,然后通过异步将请求发送到后端java控制层进行业务的逻辑处理,一下就是代码实例
添加
<#include "/common/global_css.ftl">
当数据请求到Java后端时
package com.nuocai.modules.uploadfile.controller;
import java.io.File;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.nuocai.core.common.utils.upload.FileUploadConstants;
import com.nuocai.core.mybase.Constants;
//这是请求到的具体映射路径
@Controller
@RequestMapping("/uploadfile")
public class UploadController {
@SuppressWarnings("unused")
@RequestMapping(value = { "/savephoto" }, method = RequestMethod.POST)
@ResponseBody
public String addDish(@RequestParam("photos") MultipartFile file, HttpServletRequest request) throws Exception {
String savePath = getSavePath("FILE_PATH_IMAGE");
String path = savePath;// 文件路径
double fileSize = file.getSize();
byte[] sizebyte = file.getBytes();
if (file != null) {// 判断上传的文件是否为空
String type = null;// 文件类型
String fileName = file.getOriginalFilename();// 文件原名称
fileName = reFileNameByUUID(savePath, fileName);
// 判断文件类型
type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
if (type != null) {// 判断文件类型是否为空
if ("GIF".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())) {
// 项目在容器中实际发布运行的根路径
String realPath = request.getSession().getServletContext().getRealPath("/");
// 自定义的文件名称
String trueFileName = String.valueOf(System.currentTimeMillis()) + "." + type;
// 设置存放图片文件的路径
path = savePath + fileName;
// 转存文件到指定的路径
file.transferTo(new File(path));
//返回存放该图片的具体位置加上图片命
return Constants.SAVE_FILE_IMAGE + fileName;
}
} else {
return "false";
}
} else {
return "false";
}
return "false";
}
@SuppressWarnings("unused")
@RequestMapping(value = { "/uploadSingleFile" }, method = RequestMethod.POST)
@ResponseBody
public String uploadSingleFile(@RequestParam("file_single") MultipartFile file, HttpServletRequest request) throws Exception {
String savePath = getSavePath("FILE_PATH_FILE");
String path = savePath;// 文件路径
double fileSize = file.getSize();
byte[] sizebyte = file.getBytes();
if (file != null) {// 判断上传的文件是否为空
String type = null;// 文件类型
String fileName = file.getOriginalFilename();// 文件原名称
fileName = reFileNameByUUID(savePath, fileName);
// 判断文件类型
type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
if (type != null) {// 判断文件类型是否为空
if ("DOC".equals(type.toUpperCase())||"DOCX".equals(type.toUpperCase())||"XLS".equals(type.toUpperCase())||"XLSX".equals(type.toUpperCase())||"PPT".equals(type.toUpperCase())||"PPTX".equals(type.toUpperCase())||"PDF".equals(type.toUpperCase())) {
// 项目在容器中实际发布运行的根路径
String realPath = request.getSession().getServletContext().getRealPath("/");
// 自定义的文件名称
String trueFileName = String.valueOf(System.currentTimeMillis()) + "." + type;
// 设置存放图片文件的路径
path = savePath + fileName;
// 转存文件到指定的路径
file.transferTo(new File(path));
//返回存放该附件的具体位置加上图片命
return Constants.SAVE_FILE_FILES + fileName;
}
} else {
return "false";
}
} else {
return "false";
}
return "false";
}
private static String getSavePath(String proVal) {
if (proVal != null && proVal.equals("")) {
proVal = "";
}
//获取该文件存放的具体路径
String saveFilePath = FileUploadConstants.getPropValue(proVal);
if (saveFilePath == null || saveFilePath.equals("")) {
return null;
}
if (!saveFilePath.endsWith("/"))
saveFilePath += "/";
// 生成文件保存路径
File aSaveFile = new File(saveFilePath);
if (!aSaveFile.isDirectory())
aSaveFile.mkdirs();
return saveFilePath;
}
/**
* UUID命名
*
*/
public static String reFileNameByUUID(String filePath, String fileName) {
String uFileName = UUID.randomUUID().toString();
uFileName = uFileName.substring(0, 8) + uFileName.substring(9, 13) + uFileName.substring(14, 18) + uFileName.substring(19, 23) + uFileName.substring(24);
int p = fileName.lastIndexOf(".");
fileName = uFileName + fileName.substring(p, fileName.length());
File file = new File(filePath + fileName);
if (file.exists()) {
fileName = reFileNameByUUID(filePath, fileName);
}
return fileName;
}
}
//这是处理业务逻辑的具体工具类
package com.nuocai.core.common.utils.upload;
import java.io.InputStream;
import java.util.Properties;
public class FileUploadConstants {
public static String EXCELPATH_USER = "";
private static Properties prop=null;
static{
//如果执行在Window操作系统中,则找到对应的配置文件所配置的具体文件的存放位置
String path="/config/fileUploadSavePath_windows.properties";
if(isLinux()){
//如果执行在Liunx操作系统中,则找到对应的配置文件所配置的具体文件的存放位置
path="/config/fileUploadSavePath_linux.properties";
}
//获取到输入流
InputStream in=FileUploadConstants.class.getResourceAsStream(path);
//如果存在该路径且流不为空,则读取配置文件
if(in!=null){
prop=new Properties();
try {
prop.load(in);
EXCELPATH_USER=prop.getProperty("EXCELPATH_USER");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public static String getPropValue(String key){
//如果执行在Window操作系统中,则找到对应的配置文件所配置的具体文件的存放位置
String path="/config/fileupload/fileUploadSavePath_windows.properties";
String val = null;
if(isLinux()){
//如果执行在Liunx操作系统中,则找到对应的配置文件所配置的具体文件的存放位置
path="/config/fileupload/fileUploadSavePath_linux.properties";
}
//获取到输入流
InputStream in=FileUploadConstants.class.getResourceAsStream(path);
//如果存在该路径且流不为空,则读取配置文件
if(in!=null){
prop=new Properties();
try {
prop.load(in);
val = prop.getProperty(key);
} catch (Exception e) {
e.printStackTrace();
}
}
return val;
}
//判断该代码程序是否执行在Linux操作系统当中
public static boolean isLinux(){
String osType = System.getProperties().getProperty("os.name").toLowerCase();
if(osType.startsWith("windows")){
return false;
}
else{
return true;
}
}
}
//Window配置文件所在位置 /config/fileupload/fileUploadSavePath_windows.properties 及其内容
FILE_PATH_JS=/web/project/js_css_static/js
FILE_PATH_CSS=/web/project/js_css_static/css
FILE_PATH_IMAGE=/web/project/js_css_static/image/
FILE_PATH_ATTACHMENT=/home/project/upload/attachment
FILE_PATH_IMAGERNAME=/home/project/upload/image
FILE_PATH_FTL=/web/template
FILE_PATH_COURSEITEM=/web/importcourseitem/
FILE_PATH_EXCEL=/home/project/upload/excel
PATH_ASK_CONTENT=/web/project/js_css_static/contentImage
//Linux配置文件所在位置 /config/fileupload/fileUploadSavePath_linux.properties 及其内容
FILE_PATH_JS=e:/nuocai/js
FILE_PATH_CSS=e:/nuocai/css
FILE_PATH_IMAGE=c:/web/project/js_css_static/image/
FILE_PATH_ATTACHMENT=e:/upload/attachment
FILE_PATH_FTL=e\:/userBaseInfo
FILE_PATH_IMAGERNAME=c\:/upload/image
FILE_PATH_COURSEITEM=c\:/fileupload/importcourseitem/
FILE_PATH_EXCEL=c\:/upload/excel
PATH_ASK_CONTENT=c\:/web/project/js_css_static/contentImage
PATH_ASK_CONTENT=c\:/web/project/js_css_static/contentImage
PATH_WX_APP_image=images/WXImage
//常量类所在位置
package com.nuocai.core.mybase;
import com.nuocai.core.common.utils.upload.FileUploadConstants;
import com.nuocai.core.myutil.PropertiesLoader;
/**
* 全局常量
*
* @author zj
*
*/
public abstract class Constants {
/**
* 文件存储路径
*/
public static final String SAVE_FILE_JS="http://static.gswldx.com/js/";
public static final String SAVE_FILE_CSS="http://static.gswldx.com/css/";
public static final String SAVE_FILE_IMAGE="http://static.gswldx.com/image/";
public static final String SAVE_FILE_EXCEL="http://static.gswldx.com/upload/excel/";
public static final String SAVE_FILE_FILES="http://static.gswldx.com/file/";
}
最后就是配置相关的nginx动静分离服务器
名字:static.gswldx.com.conf
server {
listen 80;
server_name static.gswldx.com;
access_log static.yijian119.com.access.log;
location / {
#location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|js|css)$ {
# valid_referers *.wafutech.com;
# if ($invalid_referer) {
# return 403;
# }
#}
root C:/web/project/js_css_static/;
#index index.html index.htm;
}
}