一、图片上传linux服务器保存、访问路径配置
我们开发图片上传功能功能时一般不考虑把图片上传到项目下的目录,否则在重新部署项目可能会因遗忘而导致图片的丢失,由此需要把图片上传放置到相应Linux目录下保存,同时为了前端可以访问,需在Tomcat中进行配置。
1、配置保存目录(ps:以下是我个人路径配置,对应后面的代码,大家可自行配置自身的路径)
# cd /usr/java/
# mkdir file
# cd file
# mkdir upload
2、Tomcat配置
--去到tomcat目录下的conf文件夹下
# cd /usr/java/tomcat7/conf/
--修改server.xml文件
# vim server.xml
--在标签下添加下面的语句
<Context docBase="/usr/java/file/upload" path="/upload" debug="0" reloadable="true"/>
最后重启Tomcat服务,到此配置就做好了。
二、java web图片上传代码开发
1、在web.xml配置上传图片的servlet
<servlet>
<servlet-name>uploadFileservlet-name>
<servlet-class>com.business.action.UploadFileservlet-class>
servlet>
<servlet-mapping>
<servlet-name>uploadFileservlet-name>
<url-pattern>/uploadFileurl-pattern>
servlet-mapping>
2、编写action类代码
代码如下:
package com.business.action;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import com.business.utils.BusinessException;
import com.business.utils.NotNullObject;
import com.business.utils.ResultCode;
import com.business.utils.ResultUtils;
import com.business.utils.ServiceUtils;
import com.business.utils.UploadFileBean;
import com.google.gson.Gson;
public class UploadFile extends HttpServlet
{
private static final long serialVersionUID = -3763233866087973330L;
protected final Logger logger = LoggerFactory.getLogger(UploadFile.class);
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
upload(request, response);
}
public void upload(HttpServletRequest request, HttpServletResponse response) throws IOException
{
//处理中文乱码
response.setContentType("application/json;charset=utf-8");
try
{
// 开始处理上传文件逻辑
String UploadResult = "";
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
// 判断请求中是否有文件上传
if (!multipartResolver.isMultipart(request))
{
UploadResult = ResultUtils.responseFail(ResultCode.E0013, "文件上传失败,系统找不到文件!");
response.getWriter().print(UploadResult);
return;
}
// 解析请求,将文件信息放到迭代器里
MultipartHttpServletRequest multiRequest = multipartResolver.resolveMultipart(request);
//校验参数
Map ParamsMap = new HashMap();
ParamsMap.put("Id", multiRequest.getParameter("Id"));
String ValidateResult = NotNullObject.isNull(ParamsMap, "Id");
if (!ResultCode.E0000.equals(ValidateResult))
{
UploadResult = ValidateResult;
response.getWriter().print(UploadResult);
return;
}
//获取文件
Iterator iter = multiRequest.getFileNames();
// 迭代文件,存放到某一路径里
while (iter.hasNext())
{
// 取得上传文件
MultipartFile file = multiRequest.getFile(iter.next());
if (null != file)
{
// 取得当前上传文件的文件名称
String myFileName = file.getOriginalFilename();
// 判断文件是否存在,文件名为空,则说明文件不存在
if (myFileName.trim() != "")
{
UploadResult = uploadFile(UploadResult, file, ParamsMap);
}
}
}
logger.info("【逻辑处理返回】" + UploadResult);
response.getWriter().print(UploadResult);
}
catch (IOException e)
{
e.printStackTrace();
logger.info(e.toString(), e);
}
}
private String uploadFile(String UploadResult, MultipartFile file, Map ParamsMap)
{
try
{
UploadFileBean bean = new UploadFileBean();
if (file != null)
{
String FilePath = bean.Upload(file);
//更新用户头像信息
ParamsMap.put("ImgPath", FilePath);
String UpdateUserResult = ServiceUtils.updateUser(ParamsMap);
if (!ResultCode.E0000.equals(UpdateUserResult))
{
UploadResult = ResultUtils.responseFail(ResultCode.E0016,"更新用户头像信息失败!");
}
else
{
Map SingleLine = new HashMap(2);
SingleLine.put("ExtName", bean.getExtName());
SingleLine.put("FilePath", FilePath);
Gson gson= new Gson();
UploadResult = ResultUtils.responseSuccess(gson.toJson(SingleLine));
}
}
else
{
UploadResult = ResultUtils.responseFail(ResultCode.E0013, "文件上传失败,系统找不到文件!");
}
}
catch (IOException e)
{
logger.info(e.toString(), e);
UploadResult = ResultUtils.responseFail(ResultCode.E0013, "文件上传失败,系统找不到文件!");
}
catch (BusinessException e)
{
logger.info(e.toString(), e);
UploadResult = ResultUtils.responseFail(e.getInfo().getCode() != null ? e.getInfo().getCode() : "9999", e.getInfo().getMessage() != null ? e.getInfo().getMessage() : "Failure");
}
return UploadResult;
}
}
package com.business.utils;
import java.io.File;
import java.io.IOException;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;
public class UploadFileBean
{
private final Logger log = Logger.getLogger(UploadFileBean.class);
private String ExtName;
public String getExtName()
{
return ExtName;
}
private void CheckFileExt(String ExtName) throws BusinessException
{
String UPLOAD_FILE_EXT_NAME = "jpg";
String[] ExtList = UPLOAD_FILE_EXT_NAME.split("\\|");
boolean ok = false;
if (ExtList != null && ExtList.length > 0)
{
for (String Ext : ExtList)
{
if (StringUtils.isNotEmpty(ExtName) && ExtName.toUpperCase().equals(Ext.toUpperCase()))
{
ok = true;
}
}
}
if (!ok)
{
ExceptionInfo info = new ExceptionInfo();
info.setCode(ResultCode.E0014);
String Message = "上传文件格式不正确!";
info.setMessage(Message);
log.error(Message);
throw new BusinessException(info);
}
}
public String Upload(MultipartFile UploadFile) throws IOException, BusinessException
{
String UPLOAD_FILE_BASE_PATH = Constants.UPLOAD_FILE_BASE_PATH;
String UPLOAD_FILE_BASE_ROOT = Constants.UPLOAD_FILE_BASE_ROOT;
String PluploadFileName = UploadFile.getOriginalFilename();
String[] FileList = PluploadFileName.split("\\.");
String ExtName = FileList[FileList.length - 1];
this.ExtName = ExtName;
//判断上传文件后缀名是否合法
CheckFileExt(ExtName);
String FileName = PluploadFileName.replace("." + ExtName, "");
String NewFileName = Md5.md5(FileName);
String Dir = NewFileName.substring(0, 2);
String NewFullName = NewFileName + "." + ExtName;
log.info("【PluploadFileName】" + PluploadFileName + "【NewFullName】" + NewFullName);
// 设置上传文件目录
String UploadPath = UPLOAD_FILE_BASE_PATH + Dir;
File _UploadFile = new File(UploadPath, NewFullName);
if (!_UploadFile.isDirectory()) _UploadFile.mkdirs();
log.info("【UploadPath】" + UploadPath);
UploadFile.transferTo(_UploadFile);
return UPLOAD_FILE_BASE_ROOT + Dir + "/" + NewFullName;
}
}
代码中包含了一些个人学习项目的业务的实现,请大家自行忽略。