上传:
1、FileService接口
package com.paic.hm.file.biz.service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.InputStream;
/**
* Created by LIMINGAN221 on 2018-03-23.
*/
public interface FileService {
/**
* 保存文件
*
* @param file
* @param originFileName
*/
String saveFile(MultipartFile file,String originFileName);
/**
* 保存文件
*
* @param file
*/
String saveFile(MultipartFile file);
/**
* 保存文件
*
* @param fileName
* @param in
* @return
*/
String saveFile(String fileName, InputStream in);
/**
* 上传文件
* @param fileName
* @param in
* @return
*/
String saveFile(String fileName, byte[] in);
/**
* 上传文件
*
* @param url
* @return
*/
File getByUrl(String url);
}
2、FileServiceImpl 接口实现
package com.paic.hm.file.biz.service.impl;
import com.paic.hm.file.biz.service.FileService;
import com.paic.hm.user.front.util.config.SystemConfigReader;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;
/**
* Created by LIMINGAN221 on 2018-03-23.
*/
@Service
public class FileServiceImpl implements FileService {
private static final String FILE_ROOT_PATH = "file.root.path";
private static final Log logger = LogFactory.getLog(FileServiceImpl.class);
@Override
public String saveFile(MultipartFile file) {
String fileName = file.getOriginalFilename();
InputStream in = null;
String result = null;
try {
in = file.getInputStream();
result = this.saveFile(fileName, in);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null) {// 关闭输入流
in.close();
}
} catch (IOException e) {
logger.error(e);
}
}
return result;
}
@Override
public String saveFile(MultipartFile file, String originFileName) {
InputStream in = null;
String result = null;
try {
in = file.getInputStream();
result = this.saveFile(originFileName, in);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null) {// 关闭输入流
in.close();
}
} catch (IOException e) {
logger.error(e);
}
}
return result;
}
@Override
public String saveFile(String fileName, InputStream in) {
FileOutputStream out = null;
try {
String rootPath = SystemConfigReader.getProperty(FILE_ROOT_PATH);
Date now = new Date();
String yyyyMM = DateFormatUtils.format(now, "yyyyMM");
String dd = DateFormatUtils.format(now, "dd");
String savePath = new StringBuffer(rootPath).append(File.separator).append(yyyyMM).append(File.separator).append(dd).toString();
File file = new File(savePath);
if (!file.exists()) {
file.mkdirs();
}
out = new FileOutputStream(new File(savePath, fileName));
// 创建一个缓冲区
byte buffer[] = new byte[1024];
// 判断输入流中的数据是否已经读完的标识
int len = 0;
// 循环将输入流读入到缓冲区当中,(len=in.read(buffer))>0就表示in里面还有数据
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
return new StringBuffer(yyyyMM).append(File.separator).append(dd).append(File.separator).append(fileName).toString();
} catch (Exception e) {
logger.info("saveFile Exception", e);
e.printStackTrace();
} finally {
try {
if (in != null) {// 关闭输入流
in.close();
}
if (out != null) {// 关闭输出流
out.close();
}
} catch (IOException e) {
logger.error(e);
}
}
return null;
}
@Override
public String saveFile(String sufix, byte[] in) {
FileOutputStream out = null;
try {
String rootPath = SystemConfigReader.getProperty(FILE_ROOT_PATH);
Date now = new Date();
String yyyyMM = DateFormatUtils.format(now, "yyyyMM");
String dd = DateFormatUtils.format(now, "dd");
String savePath = new StringBuffer(rootPath).append(File.separator).append(yyyyMM).append(File.separator).append(dd).toString();
File file = new File(savePath);
sufix=UUID()+sufix;
if (!file.exists()) {
file.mkdirs();
}
out = new FileOutputStream(new File(savePath, sufix));
out.write(in);
String fi=new StringBuffer(yyyyMM).append(File.separator).append(dd).append(File.separator).append(sufix).toString();
logger.info("saveFile byte[] ,filename="+fi);
return fi;
} catch (Exception e) {
logger.info("saveFile Exception", e);
e.printStackTrace();
} finally {
try {
if (out != null) {// 关闭输出流
out.close();
}
} catch (IOException e) {
logger.error(e);
}
}
return null;
}
private String UUID(){
String name=UUID.randomUUID().toString();
return name.replace("-", "");
}
@Override
public File getByUrl(String url) {
//下载文件路径
String path = SystemConfigReader.getProperty(FILE_ROOT_PATH);
File file = new File(path + File.separator + url);
return file;
}
}
3、上传java junit
public void uploadFile(String fileName) {
try {
// 换行符
final String newLine = "\r\n";
final String boundaryPrefix = "--";
// 定义数据分隔线
String BOUNDARY = "========7d4a6d158c9";
// 服务器的域名
URL url = new URL("http://localhost:8080/userplatforms/rest/file/upload1?loginsession=aef11049-0136-48ee-8620-4a0abc77fba6&v=2");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置为POST情
conn.setRequestMethod("POST");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 设置请求头参数
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
OutputStream out = new DataOutputStream(conn.getOutputStream());
// 上传文件
File file = new File(fileName);
StringBuilder sb = new StringBuilder();
sb.append(boundaryPrefix);
sb.append(BOUNDARY);
sb.append(newLine);
// 文件参数,photo参数名可以随意修改
sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + fileName
+ "\"" + newLine);
sb.append("Content-Type:application/octet-stream");
// 参数头设置完以后需要两个换行,然后才是参数内容
sb.append(newLine);
sb.append(newLine);
// 将参数头的数据写入到输出流中
out.write(sb.toString().getBytes());
System.out.println(sb.toString());
// 数据输入流,用于读取文件数据
DataInputStream in = new DataInputStream(new FileInputStream(
file));
byte[] bufferOut = new byte[1024];
int bytes = 0;
// 每次读1KB数据,并且将文件数据写入到输出流中
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
System.out.println(new String(bufferOut));
}
// 最后添加换行
out.write(newLine.getBytes());
in.close();
// 定义最后数据分隔线,即--加上BOUNDARY再加上--。
byte[] end_data = (newLine + boundaryPrefix + BOUNDARY + boundaryPrefix + newLine)
.getBytes();
// 写上结尾标识
out.write(end_data);
out.flush();
out.close();
// 定义BufferedReader输入流来读取URL的响应
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
}
}
4、FileUploadController
package com.paic.hm.file.web.controller;
import com.paic.hm.file.biz.service.FileService;
import com.paic.hm.user.front.web.util.ResponseUtil;
import com.paic.hm.user.front.web.util.ResultInfo;
import com.paic.pafa.web.BaseRest;
import org.apache.commons.lang.StringUtils;
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 javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
/**
* Created by LIMINGAN221 on 2018-03-23.
*/
@Controller
public class FileUploadController extends BaseRest {
@Resource
FileService fileService;
//上传文件会自动绑定到MultipartFile中
@RequestMapping(value = "/file/upload", method = RequestMethod.POST)
public ResultInfo upload(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws Exception {
String username = (String) request.getAttribute("username");
// if (StringUtils.isBlank(username)) {
// return new ResultInfo(ResponseUtil.user_or_id_not_exist_code);
// }
//如果文件不为空,写入上传路径
if (!file.isEmpty()) {
//上传文件路径
String originFileName=request.getHeader("filename");
String result = "";
if(StringUtils.isNotBlank(originFileName)){
result = fileService.saveFile(file,originFileName);
}else{
result = fileService.saveFile(file);
}
return new ResultInfo(ResponseUtil.success_code, result);
}
return new ResultInfo(ResponseUtil.param_error_code);
}
}
下载:
@RequestMapping(value = "/file/download")
public void getFileStream(HttpServletRequest request, HttpServletResponse response, String url) {
String username = (String) request.getAttribute("username");
// if (StringUtils.isBlank(username)) {
// return;
// }
url = "debug.log";
logger.info("url = " + url);
InputStream in = null;
ByteArrayOutputStream output = null;
try {
String downloadFielName = new String(url.substring(url.lastIndexOf(File.separator)+1).getBytes("UTF-8"), "iso-8859-1");
File file = fileService.getByUrl(url);
in = new FileInputStream(file);
output = new ByteArrayOutputStream();
IOUtils.copy(in, output);
byte[] buffer = output.toByteArray();
response.reset();
response.setCharacterEncoding("GB2312");
response.setHeader("Content-Length", String.valueOf(buffer.length));
response.setHeader("Content-Type", "application/x-msdownload; charset=GB2312");
response.setHeader("Content-Disposition", "attachment; filename=" + downloadFielName);
response.getOutputStream().write(output.toByteArray(), 0, output.toByteArray().length);
response.flushBuffer();
} catch (Exception e) {
logger.error("url = " + url, e);
e.printStackTrace();
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(output);
}
}
<html>
<head>
</head>
<body>
<form action="http://localhost:8080/smtapp/moduleConfigFile/upload.do" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<br>
<input type="submit" value="上传文件" />
</form>
<br>
<a href="http://localhost:8080/smtapp/moduleConfigFile/download.do?url=123.txt">123.txt</a>
</body>
</html>