超简单的一个文件的上传下载,主要是SpringMVC+Spring+MySQL数据库,里面涉及到一些工具类,可能列举不到,希望能对大家进步有帮助:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.netease.auto.sharedoc.constant.ShareConstant;
import com.netease.auto.sharedoc.constant.StatusCodeConstant;
import com.netease.auto.sharedoc.domain.Material;
import com.netease.auto.sharedoc.domain.ResultVO;
import com.netease.auto.sharedoc.domain.Row;
import com.netease.auto.sharedoc.service.IMaterialService;
import com.netease.auto.sharedoc.service.ISequenceService;
import com.netease.auto.sharedoc.util.CommonUtil;
import com.netease.auto.sharedoc.util.DateUtil;
import com.netease.auto.sharedoc.util.FileUtil;
import com.netease.auto.sharedoc.util.JsonUtil;
import com.netease.auto.sharedoc.util.RequestRenderUtil;
import com.netease.auto.sharedoc.util.RequestUtil;
import com.netease.auto.sharedoc.util.ResponseUtil;
import com.netease.auto.sharedoc.util.StringUtil;
@Controller
@RequestMapping("/share/zhaoshen")
public class ShareController {
@Autowired
IMaterialService materialService; //自己定义的service层查询类
@Autowired
ISequenceService sequenceService;//自己定义的service层查询类
/**
* 文件图片上传
* @param request
* @param response
*/
@RequestMapping("/uploadFile.json")
@ResponseBody
public void uploadFile(HttpServletRequest request, HttpServletResponse response,
@RequestParam(value = "file", required = false) MultipartFile file){//SpringMVC的参数形式以file文件形式
String statusCode = StatusCodeConstant.ERR_CODE_SUCCESS;
String statusDesc = "文件上传成功";
ResultVO vo = new ResultVO();//自己定义的一个Key_value形式的实体类
String callback = RequestUtil.get(request, "callback", "");
String encode = RequestUtil.get(request, "encode", "");
String kind = RequestUtil.get(request, "kind", "");//个人业务需求,判断是图片还是文件分开保存
//判断kind是否为空
if(StringUtils.isBlank(kind)){
vo.setStatusCode(StatusCodeConstant.ERR_CODE_PARAMETERS);
vo.setStatusDesc("上传文件所属类型不能为空");
if (callback == null || StringUtil.isBlank(callback)) {
vo.setStatusCode(statusCode);
vo.setStatusDesc(statusDesc);
ResponseUtil.write(response, JsonUtil.objectToJsonStr(vo), encode);//ResponseUtil和JsonUtil是两个自己开发的工具类,用于处理接口跨域和数据形式转化的,下面列举出来
} else {
vo.setStatusCode(statusCode);
vo.setStatusDesc(statusDesc);
ResponseUtil.write(response, callback + "(" + JsonUtil.objectToJsonStr(vo) + ")", encode);
}
}
//文件大小判断
if (file.getSize() > 1024 * 1024 * 50) { // 上传文件,最大不超过50M
vo.setStatusCode(StatusCodeConstant.ERR_CODE_PARAMETERS);
vo.setStatusDesc("上传文件,最大不超过50M!");
if (callback == null || StringUtil.isBlank(callback)) {
vo.setStatusCode(statusCode);
vo.setStatusDesc(statusDesc);
ResponseUtil.write(response, JsonUtil.objectToJsonStr(vo), encode);
} else {
vo.setStatusCode(statusCode);
vo.setStatusDesc(statusDesc);
ResponseUtil.write(response, callback + "(" + JsonUtil.objectToJsonStr(vo) + ")", encode);
}
}
try {
Material material=new Material();
String names[] = file.getOriginalFilename().split("\\.");
if(names.length > 2){
vo.setStatusCode(StatusCodeConstant.ERR_CODE_PARAMETERS);
vo.setStatusDesc("文件格式不正确请检查!");
if (callback == null || StringUtil.isBlank(callback)) {
vo.setStatusCode(statusCode);
vo.setStatusDesc(statusDesc);
ResponseUtil.write(response, JsonUtil.objectToJsonStr(vo), encode);
} else {
vo.setStatusCode(statusCode);
vo.setStatusDesc(statusDesc);
ResponseUtil.write(response, callback + "(" + JsonUtil.objectToJsonStr(vo) + ")", encode);
}
}
String datePath = DateUtil.format(new Date(),DateUtil.FORMAT_FOUR);//DateUtil日期转化的工具类
String realPath = "";
//保存文件
//1是图片2:文件
if(ArrayUtils.contains(ShareConstant.allow_img_type,file.getContentType())){
material.setMaterial_type("1");
realPath = ShareConstant.PICTURE_PATH+File.separator+datePath;
}else{
material.setMaterial_type("2");
realPath = ShareConstant.FILE_PATH+File.separator+datePath;
}
String filePath= FileUtil.uploadFile(file,realPath,names[0]); //文件上传的工具类
if(filePath ==null){
vo.setStatusCode(StatusCodeConstant.ERR_CODE_SERVER);
vo.setStatusDesc("文件上传失败");
return;
}
vo.setStatusCode(StatusCodeConstant.ERR_CODE_SUCCESS);
vo.setStatusDesc("文件上传成功");
vo.setResult(filePath);
material.setMaterial_title(names[0]);
material.setMaterial_format(file.getContentType());
material.setMaterial_url(filePath);
material.setAdmin("zhaoshen@corp.netease.com");
material.setKind(kind);
int result = materialService.saveMaterial(material);
if(result < 0){
vo.setStatusCode(StatusCodeConstant.ERR_CODE_SERVER);
vo.setStatusDesc("数据库保存失败");
if (callback == null || StringUtil.isBlank(callback)) {
vo.setStatusCode(statusCode);
vo.setStatusDesc(statusDesc);
ResponseUtil.write(response, JsonUtil.objectToJsonStr(vo), encode);
} else {
vo.setStatusCode(statusCode);
vo.setStatusDesc(statusDesc);
ResponseUtil.write(response, callback + "(" + JsonUtil.objectToJsonStr(vo) + ")", encode);
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
vo.setStatusCode(StatusCodeConstant.ERR_CODE_SERVER);
vo.setStatusDesc("服务器异常");
return;
}
if (callback == null || StringUtil.isBlank(callback)) {
vo.setStatusCode(statusCode);
vo.setStatusDesc(statusDesc);
ResponseUtil.write(response, JsonUtil.objectToJsonStr(vo), encode);
} else {
vo.setStatusCode(statusCode);
vo.setStatusDesc(statusDesc);
ResponseUtil.write(response, callback + "(" + JsonUtil.objectToJsonStr(vo) + ")", encode);
}
}
/**
* 文件图片的下载
* @param request
* @param response
*/
@RequestMapping("/downLoadFile.json")
@ResponseBody
public void downLoadFile(HttpServletRequest request, HttpServletResponse response){
String statusCode = StatusCodeConstant.ERR_CODE_SUCCESS;
String statusDesc = "文件下载成功";
ResultVO vo = new ResultVO();//自己定义的key-value形式的实体类
try {
int material_id = RequestUtil.getInt(request, "material_id",0);
Row result = materialService.getOneMaterialById(material_id);
String filePath = result.gets("material_url");
String name = result.gets("material_title");
File file = new File(filePath);
String filenames = file.getName();
String suffix = filenames.substring(filenames.lastIndexOf("."));
System.out.println("suffix ====="+suffix);
filenames = name+suffix;
// 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
String filename=new String(filenames.replaceAll(" ", "").getBytes("utf-8"), "iso8859-1");
response.reset();
response.addHeader("Content-Disposition", "attachment;filename="+filename);
response.addHeader("Content-Length", "" + file.length());
response.setContentType("application/octet-stream");//这个是重点,下载错误乱码都是在这穿线的问题
InputStream inputStream;
inputStream = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
inputStream.close();
OutputStream os = new BufferedOutputStream(response.getOutputStream());
os.write(buffer);// 输出文件
os.flush();
os.close();
vo.setStatusCode(statusCode);
vo.setStatusDesc(statusDesc);
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
}
工具类ResponseUtil:
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Response处理类
*
* @author zhaoshen
*/
public final class ResponseUtil {
private static Log logger = LogFactory.getLog(ResponseUtil.class);
/**
* Constructor
*/
private ResponseUtil() {
}
/**
* 使用response.getWriter().write(content)向客户端写数据。
*
* @param res HttpServletResponse
* @param content content
*/
public static void write(HttpServletResponse res, String content,String encode) {
PrintWriter writer = null;
try {
encode = StringUtils.isBlank(encode)?"utf-8":encode;
res.setCharacterEncoding(encode);
writer = res.getWriter();
writer.write(content);
} catch (Exception e) {
logger.error("Exception when response.", e);
} finally {
if (writer != null) {
writer.close();
}
}
}
}
文件上传的工具类
import java.io.File;
import java.util.UUID;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.multipart.MultipartFile;
public class FileUtil {
//文件上传
public static String uploadFile(MultipartFile file,String Path,String name){
if(file ==null ||StringUtils.isBlank(file.getOriginalFilename())){
return null;
}
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
String uu_name = UUID.randomUUID().toString();
String finalPath = name+uu_name+suffix;
File targetFile = new File(Path,finalPath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
try {
//保存文件
file.transferTo(targetFile);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return null;
}
return Path+File.separator+finalPath;
}
public static String getExtensionName(String filename) {
if ((filename != null) && (filename.length() > 0)) {
int dot = filename.lastIndexOf('.');
if ((dot > -1) && (dot < (filename.length() - 1))) {
return filename.substring(dot + 1);
}
}
return filename;
}
}