通过文件地址上传文件
1、webUtil工具类下载图片如下
public static void downloadImgByNet(String ServerfilePath,String filePath,String fileName){
try{
URL url = new URL(ServerfilePath);
URLConnection conn = url.openConnection();
//设置超时间为3秒
conn.setConnectTimeout(3*1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//输出流
InputStream str = conn.getInputStream();
//控制流的大小为1k
byte[] bs = new byte[1024];
//读取到的长度
int len = 0;
//是否需要创建文件夹
File saveDir = new File(filePath);
if(!saveDir.exists()){
saveDir.mkdir();
}
File file = new File(saveDir+ File.separator+fileName);
//实例输出一个对象
FileOutputStream out = new FileOutputStream(file);
//循环判断,如果读取的个数b为空了,则is.read()方法返回-1,具体请参考InputStream的read();
while ((len = str.read(bs)) != -1) {
//将对象写入到对应的文件中
out.write(bs, 0, len);
}
//刷新流
out.flush();
//关闭流
out.close();
str.close();
System.out.println("下载成功");
}catch (Exception e) {
e.printStackTrace();
}
}
** 2、上传图片接口**
@Value("${uploadfile.fileLoadPath}")
String fileLoadPath="E:\\test";
@RequestMapping(method = RequestMethod.POST, value = "/fileUpload")
public void ChangeState(@RequestBody Map param, HttpServletRequest request,
HttpServletResponse response){
String UploadfilePath="";
if (param.get("UploadfilePath")!=null){
UploadfilePath=param.get("UploadfilePath").toString();
}
String fileName="";
if (param.get("fileName")!=null){
fileName=param.get("fileName").toString();
}
WebUtil.downloadImgByNet(UploadfilePath,fileLoadPath,fileName);
}
通过文件传入并存放服务器
@Value("${uploadfile.fileLoadPath}")
String fileLoadPath="E:\\test";
/**
* 文件的上传
* @param file
* @return
*/
@RequestMapping(value = "/uploads",method = RequestMethod.POST)
public void upload(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
// 判断文件是否为空
String path = fileLoadPath;
HashMap<String, String> message = new HashMap<>();
if (!file.isEmpty()) {
try {
// 文件保存路径
String filePath = path + "/" + file.getOriginalFilename();
if (!new File(filePath).exists()){
new File(filePath).mkdirs();
}
// 转存文件
file.transferTo(new File(filePath));
message.put("status", filePath);
} catch (Exception e) {
// e.printStackTrace();
message.put("status", "error");
}
}
renderResult(response, message);
}
上传并生成随即名
@Value("${uploadfile.fileLoadPath}")
String fileLoadPath="E:\\test";
/**
* 文件的上传
* @param file
* @return
*/
@RequestMapping(value = "/upload",method = RequestMethod.POST)
public void upload(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
// 判断文件是否为空
String path = fileLoadPath;
HashMap<String, String> message = new HashMap<>();
if (!file.isEmpty()) {
try {
// 文件保存路径
// String filePath = path + "/" + file.getOriginalFilename();
String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); //获取文件的后缀名
String filePath = path+"\\"+UUID.randomUUID().toString().replace("-","")+suffixName; //拼接
if (!new File(filePath).exists()){
new File(filePath).mkdirs();
}
// 转存文件
file.transferTo(new File(filePath));
message.put("status", filePath);
} catch (Exception e) {
// e.printStackTrace();
message.put("status", "error");
}
}
renderResult(response, message);
}
以base64编码上传文件
以下为base64的编码和解码的工具类
public class FileBase64Utils {
/**
* 本地文件(图片、excel等)转换成Base64字符串
*
* @param file 接受的文件
*/
public static String convertFileToBase64(MultipartFile file) {
byte[] data = null;
// 读取图片字节数组
try {
InputStream in = file.getInputStream();
// InputStream in = new FileInputStream(imgPath);
System.out.println("文件大小(字节)=" + in.available());
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组进行Base64编码,得到Base64编码的字符串
Base64.Decoder decoder = Base64.getDecoder();
Base64.Encoder encoder = Base64.getEncoder();
String base64Str = encoder.encodeToString(data);
return base64Str;
}
/**
* 将base64字符串,生成文件
*/
public static File convertBase64ToFile(String fileBase64String, String filePath, String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File(filePath);
if (!dir.exists() && dir.isDirectory()) {//判断文件目录是否存在
dir.mkdirs();
}
Base64.Decoder decoder = Base64.getDecoder();
Base64.Encoder encoder = Base64.getEncoder();
// BASE64Decoder decoder = new BASE64Decoder();
byte[] bfile = decoder.decode(fileBase64String);
file = new File(filePath + File.separator + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bfile);
return file;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
上传附件的接口如下
/**
* 附件上传接口
* @param request
* @param response
* @param file 前端传来的附件
*/
@RequestMapping(method = RequestMethod.POST, value = "/uploadFile")
public void uploadFile(HttpServletRequest request,
HttpServletResponse response, MultipartFile file){
Map<String,Object> res = new HashMap<String, Object>();
try{
long start = System.currentTimeMillis(); //获取开始的时间
String filename = file.getOriginalFilename(); //获取文件名
String imgBase64Str = FileBase64Utils.convertFileToBase64(file); //使用base64对文件编码成字符串格式
System.out.println("Base64字符串length=" + imgBase64Str.length()); //得到编码后的长度
// 如果文件不存在,则创建
if (!new File(ServerloadPath).exists()){
new File(ServerloadPath).mkdirs();
}
// 重新将字符串解码为文件类型并上传
File file1 = FileBase64Utils.convertBase64ToFile(imgBase64Str, ServerloadPath, filename);
assert file1 != null;
String absolutePath = file1.getAbsolutePath();
// 输入花费时间
System.out.println("duration:" + (System.currentTimeMillis() - start));
// 返回存放地址
res.put("filePath", absolutePath);
res.put("duration",System.currentTimeMillis() - start+"ms");
renderResult(response, res);
}catch(Exception ex){
ex.printStackTrace();
}
}
如有不对的地方,欢迎指点