spring mvc 文件上传搭建
上传 控制器代码:
@Controller
public class FileController implements BindingResultMessage{
@Autowired
private FileShareService fileShareService;
private FileSaveCategory fileSaveCategory = new DateAppendSaveCategory();
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public Map<String,Object> upload(HttpServletRequest req) throws IOException {
Map<String,Object> retMap = Maps.newHashMap();
retMap.put("statusCode",StatusCode.SUCCESS);
Map<String,Object> result = Maps.newHashMap();
CommonsMultipartResolver resolver = new CommonsMultipartResolver(
req.getServletContext());
if (resolver.isMultipart(req)) {
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) req;
// 取得request中的所有文件名
Iterator<String> iter = multiRequest.getFileNames();
FileShare record = null;
String path = null;
List<FileShare> list = Lists.newArrayList();
String prefix = "";
if(fileSaveCategory != null){
prefix = fileSaveCategory.prefixPath();
}
while (iter.hasNext()) {
String fileName = iter.next();
// 取得上传文件
List<MultipartFile> mfs = multiRequest.getFiles(fileName);
for(MultipartFile file:mfs){
String originalFilename = file.getOriginalFilename();
path = com.yaochfua.jframework.fileshare.core.Files.save(file,prefix);
//入库
record = new FileShare();
record.setName(originalFilename);
record.setPath(GlobalVar.fileDownloadServer+path);
fileShareService.insert(record);
list.add(record);
}
}
result.put("data",list);
retMap.put("result",result);
}
return retMap;
}
}
说明:
1)上传的文件保存到一个固定文件夹,然后通过nginx配置一个静态资源下载服务器。
2)接口直接返回文件的下载路径。
nginx下载服务配置
nginx.conf 关键配置(标红部分)
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
<span style="color:#ff0000;"> </span><pre code_snippet_id="1772998" snippet_file_name="blog_20160720_2_3025468" name="code" class="plain"><span style="color:#ff0000;"> location /fileShare {
alias /data/fileRootDir/;
}</span>
说明 :将/data/fileRootDir 当作一个下载资源根路径 所有上传的文件放在改路径或者子路径下。
java后台调用上传文件接口
代码为:
public final class FileUploadUtil {
public static JSONObject upload(String httpurl, String fileName, InputStream inputStream) {
String result = "";
try {
String BOUNDARY = "---------7d4a6d158c9"; // 定义数据分隔线
URL url = new URL(httpurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + BOUNDARY);
OutputStream out = new DataOutputStream(conn.getOutputStream());
byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// 定义最后数据分隔线
StringBuilder sb = new StringBuilder();
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"file" + 1
+ "\";filename=\"" + fileName + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] data = sb.toString().getBytes();
out.write(data);
DataInputStream in = new DataInputStream(inputStream);
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
out.write("\r\n".getBytes()); // 多个文件时,二个文件之间加入这个
in.close();
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) {
result+=line;
}
} catch (Exception e) {
System.out.println("发送POST请求出现异常!" + e);
}
return JSONObject.parseObject(result);
}
public static void main(String[] args) throws Exception {
String content ="hellow 中国";
InputStream ips = new ByteArrayInputStream(content.getBytes("UTF-8"));
System.out.println(upload("http://192.168.9.21:8082/fileShare/upload","text.txt",ips));
}
}
PS:
1)linux nginx安装注意去官网下载源代码编译安装,不要利用yum install (熟悉的人倒也无所谓),运维同事建议我源码编译安装。
2)上传接口:
http://192.168.9.21:8082/fileShare/upload
返回数据
{
result: {
data: [
{
name: "",
path: "http://192.168.9.21/fileShare/2016/0720/7269220160720"
},
{
name: "搜索绘图.xls",
path: "http://192.168.9.21/fileShare/2016/0720/9558420160720.xls"
}
]
},
statusCode: 0
}