import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
//发送接口
public class FileUpload {
static String url="http://******/aa";
static HttpClient httpClient=HttpClientBuilder.create().build();
@RequestMapping("/ccc")
public static Object uploadFile(){
File file = new File("D:\\abcd");//需要查找的文件夹
File[] files = file.listFiles(); //将路径封装成File数组
try {
for (File file2 : files) {//遍历这个数组
String regex="(.*)jpg";
if (file2.isDirectory()) { //判断是否是文件夹
// copyPhoto(file2); //是的话就继续调用这个方法
} else if (file2.getName().matches(regex)) { //不是的话就匹配是否是图片
HttpPost post=new HttpPost(url);
HttpEntity entity=MultipartEntityBuilder.create()
.addBinaryBody("file", file2).build();
post.setEntity(entity);
HttpResponse httpResponse=httpClient.execute(post);
HttpEntity respEntity=httpResponse.getEntity();
String resuiltEntity=EntityUtils.toString(respEntity);
System.out.println(resuiltEntity);
//一下是备份文件
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(file2)) ;//创建输入的管道
byte[] buf = new byte[1024*20];//创建一个小数组
int lenght = 0;
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream( //创建输出管道
"D:\\awdc\\" + file2.getName())); //图片会拷贝到这里
while ((lenght=bis.read(buf)) != -1) {
bos.write(buf, 0, lenght);
}
bos.close();
bis.close();
file2.delete();//删除指定文件
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
//接收接口
@RequestMapping("/aa")
public String FilePicture(@RequestParam(value="file",required=false)
MultipartFile file ) {
if (file!=null) {
String fileName=file.getOriginalFilename();
try {
BufferedInputStream bis=new BufferedInputStream(file.getInputStream()) ;//创建输入的管道
byte[] buf = new byte[1024*20];//创建一个小数组
int lenght = 0;
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream( //创建输出管道
"D:\\awd\\" + fileName)); //图片会拷贝到这里
while ((lenght=bis.read(buf)) != -1) {
bos.write(buf, 0, lenght);
}
bos.close();
bis.close();
} catch (Exception e) {
}
System.out.println("success");
}
return "200";
}
//pom.xml
<dependency>
<groupId>org.apache.myfaces.tobago</groupId>
<artifactId>tobago-fileupload</artifactId>
<version>2.0.9</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.6</version>
</dependency>