package com.fh.util;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
public class FileUpload {
public static String fileUp(MultipartFile file, String filePath, String fileName){
String extName = "";
try {
if (file.getOriginalFilename().lastIndexOf(".") >= 0){
extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
}
copyFile(file.getInputStream(), filePath, fileName+extName).replaceAll("-", "");
} catch (IOException e) {
System.out.println(e);
}
return fileName+extName;
}
public static String copyFile(InputStream in, String dir, String realName)
throws IOException {
File file = mkdirsmy(dir,realName);
FileUtils.copyInputStreamToFile(in, file);
in.close();
return realName;
}
public static File mkdirsmy(String dir, String realName) throws IOException{
File file = new File(dir, realName);
if (!file.exists()) {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
}
return file;
}
public static String getHtmlPicture(String httpUrl, String filePath , String myFileName) {
URL url;
BufferedInputStream in;
FileOutputStream file;
try {
String fileName = null == myFileName?httpUrl.substring(httpUrl.lastIndexOf("/")).replace("/", ""):myFileName;
url = new URL(httpUrl);
in = new BufferedInputStream(url.openStream());
file = new FileOutputStream(mkdirsmy(filePath,fileName));
int t;
while ((t = in.read()) != -1) {
file.write(t);
}
file.close();
in.close();
return fileName;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
package com.fh.util;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletResponse;
public class FileDownload {
public static void fileDownload(final HttpServletResponse response, String filePath, String fileName) throws Exception{
byte[] data = FileUtil.toByteArray2(filePath);
fileName = URLEncoder.encode(fileName, "UTF-8");
response.reset();
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
response.addHeader("Content-Length", "" + data.length);
response.setContentType("application/octet-stream;charset=UTF-8");
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
outputStream.write(data);
outputStream.flush();
outputStream.close();
response.flushBuffer();
}
}