resource:
uploadurl: /home/workspace/upload #服务器文件上传地址
domain: http://192.168.9.105/resourcecenterupload/ #nginx映射地址
extendNames: jpg,png,rar,ppt,pptx,txt,zip,doc,pdf,docx,xlsx,xls #可上传哪些文件
package cc.cloud.resourcecenter.web.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import cc.cloud.resourcecenter.config.ThreadLocalCurrentUser;
import cc.cloud.resourcecenter.core.model.UploadResult;
import cc.cloud.resourcecenter.core.model.auth.CurrentUser;
import cc.cloud.resourcecenter.util.io.IOUtil;
import cc.cloud.resourcecenter.web.service.UploadService;
import lombok.extern.slf4j.Slf4j;
/**
* <p>Title: UploadController</p>
* <p>Description: </p>
* @date 2019年4月12日
*/
@Controller
@Slf4j
@RequestMapping(value="/upload")
public class UploadController {
@Value("${resource.uploadurl}")
private String serverUrl;
@Value("${resource.extendNames}")
private String extendNames;
@Autowired
private UploadService uploadService;
/**
*
* <p>Title: uploadfile</p>
* <p>Description: 传文件 由于ie 浏览器兼容性问题, 对于较低版本的IE 浏览器 采用iframe 上传文件后,
* 返回 json格式数据 ie会提示下载.所以返回text/plain 格式数据,兼容所有客户端</p>
* @param request
* @param response
* @param key
* @param file
* @return
* @throws IOException
*/
@RequestMapping(value="/uploadfile", method = RequestMethod.POST)
@ResponseBody
public List<Map<String, Object>> uploadfile(HttpServletRequest request, HttpServletResponse response,
@RequestParam MultipartFile[] files) throws IOException {
CurrentUser currentUser = ThreadLocalCurrentUser.getCurrentUser();
Integer schoolId = currentUser.getSchoolId();
Map<String, Object> map = null;
List<Map<String, Object>> listMap = null;
if (files!=null&&files.length>0) {
listMap = new ArrayList<>();
map = new HashMap<>();
for (MultipartFile file : files) {
//文件大小
long fileSize = file.getSize();
// 文件后缀名称
String extendName = IOUtil.getExtendName(file.getOriginalFilename());
if (!extendNames.contains(extendName)) {
map.put("status", -1);
map.put("reason", "该文件后缀:"+extendName+"不允许上传");
listMap.add(map);
}else {
UploadResult uploadResult=uploadService.uploadFile(serverUrl,file,schoolId);//保存到服务器的路径
uploadResult.setFileSize(fileSize);
if (uploadResult.getCode() == 0) {
map.put("status", 0);
map.put("reason", "上传成功");
map.put("data", uploadResult);
}else{
map.put("status", -1);
map.put("reason", "上传失败");
map.put("data", new UploadResult(-1));
}
listMap.add(map);
map = new HashMap<>();
}
}
}
return listMap;
}
}
package cc.cloud.resourcecenter.web.service;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import javax.annotation.Resource;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import cc.cloud.resourcecenter.core.entity.ResourceCenterAccessory;
import cc.cloud.resourcecenter.core.mapper.ResourceCenterMapper;
import cc.cloud.resourcecenter.core.model.UploadResult;
import cc.cloud.resourcecenter.util.io.IOUtil;
/**
* @ClassName: UploadService
* @Description: (上传附件)
* @date 2019年6月11日 上午9:26:41
* @version V1.0
*
*/
@Service
public class UploadService {
@Value("${resource.domain}")
private String domain;
@Resource
private ResourceCenterMapper resourceCenterMapper;
/**
* <p>Title: uploadFile</p>
* <p>Description: </p>
* @param serverUrl
* @param key
* @param file
* @return
* @throws IOException
* @throws IllegalStateException
*/
@Transactional(rollbackFor = Exception.class)
public UploadResult uploadFile(String serverUrl, MultipartFile fileHandler, Integer schoolId){
System.out.println("name: " + fileHandler.getOriginalFilename() + " size: " + fileHandler.getSize());
//要上传的文件夹是否存在
//先通过key找到对应的存放目录(找到可以上传的文件格式 磁盘目录)
//判断磁盘目录是否存在,不存在创建文件夹
//文件写入到文件夹中
//文件后缀 例如txt
String extendName = IOUtil.getExtendName(fileHandler.getOriginalFilename());
UploadResult uploadResult = new UploadResult(0);
String fileUri=null;
try {
//附件上传地址
serverUrl+="/resource/center/";
//附件相应地址
fileUri="resource/center/";
System.out.println("serverUrl: " + serverUrl);
File file = new File(serverUrl);
if (!file.exists()) {
file.mkdirs();
}
// MultipartFile转File
FileUtils.copyInputStreamToFile(fileHandler.getInputStream(), new File(file, fileHandler.getOriginalFilename()));
File copyFile = new File(file.getPath()+"/"+fileHandler.getOriginalFilename());
String resourceMdf = getFileMD5(copyFile);
// 查询是否存在该文件
ResourceCenterAccessory getRcy = resourceCenterMapper.getResourceCenterAccessory(resourceMdf);
String fileName=resourceMdf+"."+extendName;
String fileUrl = serverUrl + fileName;
if (getRcy==null) {
FileOutputStream fos = null;
fos = new FileOutputStream(fileUrl);
fos.write(fileHandler.getBytes()); // 写入文件
fos.close();
String fileServerUrl = domain+fileUri+fileName;
ResourceCenterAccessory resourceCenterAccessory = new ResourceCenterAccessory();
resourceCenterAccessory.setSchoolId(schoolId);
resourceCenterAccessory.setResourceMdf(resourceMdf);
resourceCenterAccessory.setUrl(fileServerUrl);
resourceCenterMapper.saveResourceCenterAccessory(resourceCenterAccessory);
uploadResult.setId(resourceCenterAccessory.getId());
// uploadResult.setUrl(fileServerUrl);
}else {
uploadResult.setId(getRcy.getId());
// uploadResult.setUrl(getRcy.getUrl());
}
// uploadResult.setUrl(serverUrl+fileName);
uploadResult.setName(new String(fileHandler.getOriginalFilename().getBytes("utf-8"),"utf-8"));
// uploadResult.setResourceMdf(resourceMdf);
// 删除复制出来的文件
copyFile.delete();
} catch (Exception e) {
uploadResult = new UploadResult(-1);
e.printStackTrace();
return uploadResult;
}
return uploadResult;
}
/**
* @Title: getFileMD5
* @Description: (将文件md5)
* @param @param file
* @param @return 设定文件
* @return String 返回类型
* @throws
*/
public static String getFileMD5(File file) {
if (!file.isFile()) {
return null;
}
MessageDigest digest = null;
FileInputStream in = null;
byte buffer[] = new byte[8192];
int len;
try {
digest =MessageDigest.getInstance("MD5");
in = new FileInputStream(file);
while ((len = in.read(buffer)) != -1) {
digest.update(buffer, 0, len);
}
BigInteger bigInt = new BigInteger(1, digest.digest());
return bigInt.toString(16);
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
package cc.cloud.resourcecenter.core.model;
/**
* <p>Title: UploadResult</p>
* <p>Description: </p>
* @date 2019年4月12日
*/
public class UploadResult {
private Integer id;
private int code;
private String name;
private String url;
private long fileSize;
private String resourceMdf;//md5值
public String getResourceMdf() {
return resourceMdf;
}
public void setResourceMdf(String resourceMdf) {
this.resourceMdf = resourceMdf;
}
/**
* @return the fileSize
*/
public long getFileSize() {
return fileSize;
}
/**
* @param fileSize the fileSize to set
*/
public void setFileSize(long fileSize) {
this.fileSize = fileSize;
}
public UploadResult(int code) {
this.code = code;
}
public UploadResult(Integer id, int code, String name, String url,long fileSize, String resourceMdf) {
this.id = id;
this.code = code;
this.name = name;
this.url = url;
this.fileSize = fileSize;
this.resourceMdf = resourceMdf;
}
public int getCode() {
return this.code;
}
public String getName() {
return this.name;
}
public String getUrl() {
return this.url;
}
public void setResult(int code) {
this.code = code;
}
public void setName(String name) {
this.name = name;
}
public void setUrl(String url) {
this.url = url;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (!(o instanceof UploadResult)) {
return false;
} else {
UploadResult other = (UploadResult) o;
if (!other.canEqual(this)) {
return false;
} else if (this.getCode() != other.getCode()) {
return false;
} else {
String this$name = this.getName();
String other$name = other.getName();
if (this$name == null) {
if (other$name != null) {
return false;
}
} else if (!this$name.equals(other$name)) {
return false;
}
String this$url = this.getUrl();
String other$url = other.getUrl();
if (this$url == null) {
if (other$url != null) {
return false;
}
} else if (!this$url.equals(other$url)) {
return false;
}
return true;
}
}
}
protected boolean canEqual(Object other) {
return other instanceof UploadResult;
}
public int hashCode() {
boolean PRIME = true;
byte result = 1;
int result1 = result * 59 + this.getCode();
String $name = this.getName();
result1 = result1 * 59 + ($name == null ? 0 : $name.hashCode());
String $url = this.getUrl();
result1 = result1 * 59 + ($url == null ? 0 : $url.hashCode());
return result1;
}
public String toString() {
return "UploadResult(result=" + this.getCode() + ", name=" + this.getName() + ", url=" + this.getUrl() + ", id=" + this.getId() +")";
}
}
#nginx配置:
location /resourcecenterupload/ {
#proxy_pass http://127.0.0.1:8801/;
proxy_pass http://192.168.9.110:8801/;
# proxy_pass http://cp/;
proxy_redirect off;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_max_temp_file_size 0;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
client_max_body_size 1000m;
}