编辑nginx.conf内容
cd /usr/local/nginx/conf
vi nginx.conf
内容如下所示:
error_log logs/error.log error ;
pid logs/nginx.pid;
user root;
worker_processes auto;
worker_rlimit_nofile 51200;
events {
use epoll;
worker_connections 51200;
}
http {
client_body_buffer_size 32k;
client_header_buffer_size 2k;
client_max_body_size 100m;
default_type application/octet-stream;
log_not_found off;
server_tokens off;
include mime.types;
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.0;
gzip_comp_level 2;
gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml application/rss+xml application/xhtml+xml application/atom_xml;
gzip_vary on;
#error_page 500 502 503 504 /50x.html;
log_format access '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" $http_x_forwarded_for';
server {
listen 8785; ## 8785指定端口
server_name test.dgd.com; ##域名,
root /data/images; ##图片实际存储的位置,如果没有对应的目录先创建
access_log /var/logs/nginx/access/images.log;
location ~ .*\.(gif|jpg|jpeg|png)$ {
proxy_store on;
proxy_temp_path /data/images;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 10m;
client_body_buffer_size 1280k;
proxy_connect_timeout 900;
proxy_send_timeout 900;
proxy_read_timeout 900;
proxy_buffer_size 40k;
proxy_buffers 40 320k;
proxy_busy_buffers_size 640k;
proxy_temp_file_write_size 640k;
if ( !-e $request_filename)
{
proxy_pass http://127.0.0.1:8785;
}
}
}
}
java 代码示例:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.Map;
@Controller
@RequestMapping("/import")
public class ImportController {
private static Logger logger = LoggerFactory.getLogger(ImportController.class);
@RequestMapping(value = "upload",method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity uploadGoodsSupplierData(@RequestParam MultipartFile file,MultipartHttpServletRequest request) {
ResponseJsonRender resultData = new ResponseJsonRender("上传成功");
try {
if (file != null) {
String url = getUploadFileUrl(file, request);
log.info("图片访问路径:"+url);
}else{
resultData.setCode(-100);
resultData.setMsg("没有发现可用的文件");
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
resultData.setCode(-100);
resultData.setMsg(e.getMessage());
}
return new ResponseEntity(resultData, HttpStatus.OK);
}
/**
* 获取文件的路径
* @param file
* @param request
* @return
* @throws Exception
*/
private String getUploadFileUrl(MultipartFile file,
MultipartHttpServletRequest request) throws Exception {
//判断文件是否图片文件
FileHelper.isFileFormatIMG(file);
//获取上传文件的地址
String imgName = FileHelper.getFileName4Saving(file.getOriginalFilename());
String imgUrl = File.separator + imgName;
String fullPath = FileHelper.generateParentFolder(request) + imgUrl;
//保存文件
FileHelper.save(file, fullPath);
//生成访问的图片URL
String path = FileHelper.generateFolderHttp(request)+"/"+imgName;
return FileHelper.generateParentFolderURL(request,path);
}
}
用到的工具类
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.UUID;
@Component
public class FileHelper {
private static Logger logger = LoggerFactory.getLogger(FileHelper.class);
private static final String[] XLS_EXTENSION = new String[]{"xls", "xlsx"};
private static final String[] IMG_EXTENSION=new String[]{"jpg","jpeg","gif","png"};
private static String SERVER_IMAGE_URL; // 指定图片文件url的前缀
private static String SERVER_IMAGE_PATH; //图片实际存储的路径
//从配置文件中读取常量
@Value("#{application['server.image.url']}")
public void setServerImageUrl(String serverImageUrl) {
this.SERVER_IMAGE_URL = serverImageUrl;
}
@Value("#{application['server.image.path']}")
public void setServerImagePath(String serverImagePath) {
this.SERVER_IMAGE_PATH = serverImagePath;
}
public static boolean isFileFormatXLS(MultipartFile file) {
if (!FilenameUtils.isExtension(file.getOriginalFilename().toLowerCase(), XLS_EXTENSION)) {
throw new BsRuntimeExceptioin("文件解析错误",-100);
}
return true;
}
public static boolean isFileFormatIMG(MultipartFile file) {
if (!FilenameUtils.isExtension(file.getOriginalFilename().toLowerCase(), IMG_EXTENSION)) {
throw new BsRuntimeExceptioin("文件解析错误", -100);
}
return true;
}
public static String getBasePath() {
logger.info("当前存放的路径是:"+SERVER_IMAGE_PATH);
return SERVER_IMAGE_PATH;
}
public static void createParentFolder(String fullParentFolderPath) {
File fullParentFolder = new File(fullParentFolderPath);
if (!fullParentFolder.exists()) {
fullParentFolder.mkdirs();
}
}
public static String generateParentFolder(HttpServletRequest request) {
String folder=generateFolder(request);
String fullParentFolderPath = getBasePath() + folder;
createParentFolder(fullParentFolderPath);
return fullParentFolderPath;
}
//保存文件
public static void save(MultipartFile file, String fullPath) {
try {
try (FileOutputStream os = new FileOutputStream(fullPath)) {
os.write(file.getBytes());
os.flush();
}
} catch (Exception e) {
logger.error("Error occurs when saving file: ", e);
}
}
//将文件URL前缀+生成的路径拼起来
public static String generateParentFolderURL(HttpServletRequest request,String path){
return SERVER_IMAGE_URL+"/"+path;
}
public static String generateFolderHttp(HttpServletRequest request) {
String type = request.getParameter("folder");
String folder = (type == null ? "data" : "data/" + type);
Calendar calendar = Calendar.getInstance();
//将文件按指定路径+年+月+日的格式路径存储
return folder +
"/"+ calendar.get(Calendar.YEAR) +
"/" + (calendar.get(Calendar.MONTH) + 1) + "/" + calendar.get(Calendar.DATE);
}
public static String getFileName4Saving(String fileName) {
return UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
}
}
配置文件:application.properties
#图片发布地址,跟Nginx配置的域名和端口必须一致
server.image.url=http://test.dgd.com:8785
#图片实际存储的路径(服务器为Linux系统),如果没有该文件目录先创建
server.image.path=/data/images/
为了能让FileHelper 类里的@Value(“#{application[‘server.image.url’]}”)
注解能正确读取配置文件里的值,需要在applicationContext.xml配置如下内容:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
"
default-autowire="byType"
>
<!--启动spring MVC 注解-->
<context:annotation-config />
<!-- 定义扫描的包路径 -->
<context:component-scan base-package="com"/>
<!-- 加载配置属性文件 -->
<util:properties id="application" location="file:application.properties"></util:properties>
</beans>