1.文件上传有两种一种是流(instream),另一种是路径(url)的方式
1.1:判断服务器类型window还是linux
public static boolean isLinux() {
return System.getProperty("os.name").toLowerCase().indexOf("linux") >= 0;
}
public static boolean isWindows() {
return System.getProperty("os.name").toLowerCase().indexOf("windows") >= 0;
}
if (isWindows()) {
fullPathName = path + "\\" + filename;
} else {
fullPathName = path + "/" + filename;
}
1.2:文件存储写入磁盘
FileOutputStream fs = new FileOutputStream(fullPathName);
byte[] buffer = null;
if (fileSize > (1024 * 1024)) {
buffer = new byte[1024 * 1024];
} else {
buffer = new byte[fileSize];
}
int byteread = 0;
while ((byteread = is.read(buffer)) != -1) {
fs.write(buffer, 0, byteread);
fs.flush();
}
fs.close();
is.close();
1.3:将文件路径url转为流(instrenm)
InputStream file = new FileInputStream(filenurl);
1.4:获取文件的类型或者名字方法
String suffix = filenurl.substring(filenurl.lastIndexOf("."), filenurl.length());
String fileName=new File(filenurl).getName();
1.5:如果是多文件上传的需要先获取全部的文件出来MultipartFile
List<MultipartFile> multipartFiles = request.getMultiFileMap().get("file_data");
if (null == multipartFiles || multipartFiles.size() == 0) {
result.put("error", "无法获取需要处理的文件信息");
return result;
}
for (int i = 0; i < multipartFiles.size(); i++) {
MultipartFile multipartFile = multipartFiles.get(i);
InputStream is= multipartFile.getInputStream();
}
1.6:文件上传代码
public static String sendPostUplodFile(String in11) {
DataOutputStream out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL("http://localhost:8102/fileserver/upload?BusiessId=24");
HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();
String BOUNDARY = "----WebKitFormBoundary07I8UIuBx6LN2KyY";
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);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
out = new DataOutputStream(conn.getOutputStream());
File file = new File(String.valueOf(in11));
StringBuffer sb = new StringBuffer();
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"file_data\";filename=\"" + file.getName() + "\"");
sb.append("\r\n");
sb.append("Content-Type: application/octet-stream");
sb.append("\r\n");
sb.append("\r\n");
out.write(sb.toString().getBytes());
FileInputStream in1 = new FileInputStream(file);
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in1.read(bufferOut)) != -1) {
out.write(bufferOut,0,bytes);
}
out.write("\r\n".getBytes());
in1.close();
byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(end_data);
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
return result;
}
1.7:流形式的文件保存,下载代码
private void savePic(InputStream inputStream, String fileName) {
OutputStream os = null;
try {
String path = "D:\\testFile\\";
byte[] bs = new byte[1024];
int len;
File tempFile = new File(path);
if (!tempFile.exists()) {
tempFile.mkdirs();
}
os = new FileOutputStream(tempFile.getPath() + File.separator + fileName);
while ((len = inputStream.read(bs)) != -1) {
os.write(bs, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
os.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
1.7:URL形式的文件保存,下载代码
public static File saveUrlAs( String pdfUrl) {
File file = new File("D:\\testFile");
if (!file .exists()) {
file .mkdirs();
}
FileOutputStream fileOut = null;
HttpURLConnection conn = null;
InputStream inputStream = null;
try {
URL httpUrl = new URL(pdfUrl);
conn = (HttpURLConnection) httpUrl.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.connect();
inputStream = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(inputStream);
fileOut = new FileOutputStream("D:\\testFile\\" + "test.pdf");
BufferedOutputStream bos = new BufferedOutputStream(fileOut);
byte[] buf = new byte[4096];
int length = bis.read(buf);
while (length != -1) {
bos.write(buf, 0, length);
length = bis.read(buf);
}
bos.close();
bis.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
System.out.println("抛出异常!!");
}
return file;
}
1.8:URL(远程)形式的上传文件
public static String sendPostUplodFile2(String in11) throws IOException {
DataOutputStream out = null;
BufferedReader in = null;
String result = "";
HttpURLConnection conn1 = null;
InputStream inputStream = null;
BufferedInputStream bis=null;
try {
URL httpUrl = new URL(in11);
conn1 = (HttpURLConnection) httpUrl.openConnection();
conn1.setRequestMethod("GET");
conn1.setDoInput(true);
conn1.setDoOutput(true);
conn1.setUseCaches(false);
conn1.connect();
inputStream = conn1.getInputStream();
URL realUrl = new URL("上传文件服务器的URL");
HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
String BOUNDARY = "----WebKitFormBoundary07I8UIuBx6LN2KyY";
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
conn.connect();
out = new DataOutputStream(conn.getOutputStream());
byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
StringBuffer sb = new StringBuffer();
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"file_data\";filename=\"" + "pdf.pdf" + "\"");
sb.append("\r\n");
sb.append("Content-Type: application/octet-stream");
sb.append("\r\n");
sb.append("\r\n");
out.write(sb.toString().getBytes());
DataInputStream in1 = new DataInputStream(inputStream);
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in1.read(bufferOut)) != -1) {
out.write(bufferOut,0,bytes);
}
out.write("\r\n".getBytes());
in1.close();
out.write(end_data);
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (conn1!=null) {
conn1.disconnect();
}
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
}
return result;
}
1.9:pdf预览图片预览或者下载
@GetMapping("/viewFile")
public void downFile(HttpServletResponse response, HttpServletRequest request) {
try {
File file = new File("C:\\xx.pdf");
String filename = file.getName();
String fileType = filename.substring(filename.indexOf(".") + 1);
FileInputStream fileInputStream = new FileInputStream(file);
InputStream fis = new BufferedInputStream(fileInputStream);
byte[] buffer = new byte[1024];
int len = 0;
response.reset();
response.addHeader("Access-Control-Allow-Origin", "*");
boolean b = "jpg".equalsIgnoreCase(fileType) || "png".equalsIgnoreCase(fileType) || "gif".equalsIgnoreCase(fileType);
if (b) {
response.setContentType("image/" + fileType);
} else if ("pdf".equalsIgnoreCase(fileType)) {
response.setContentType("application/pdf");
} else {
response.setContentType("application/text;chartset=utf-8");
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
response.addHeader("Content-Length", "" + file.length());
}
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
int a = 0;
while ((len = fis.read(buffer)) != -1) {
a = len + a;
toClient.write(buffer, 0, len);
}
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}