我必须编写一个spring boot方法,我必须下载从另一个微服务返回的文件。 谁能告诉我怎么办呢。
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.StandardCopyOption;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
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.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
public File processFile(MultipartFile uploadedFile) throws IllegalStateException, IOException {
if (!uploadedFile.isEmpty()) {
byte[] bytes = uploadedFile.getBytes();
String fileName = uploadedFile.getOriginalFilename();
File convertedFile = new File(uploadedFile.getOriginalFilename());
uploadedFile.transferTo(convertedFile);
OkHttpClient.Builder builder = new OkHttpClient.Builder();
OkHttpClient client = builder.readTimeout(120, TimeUnit.SECONDS).writeTimeout(120, TimeUnit.SECONDS)
.connectTimeout(120, TimeUnit.SECONDS).build();
MediaType mediaType = MediaType
.parse("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("file", fileName, RequestBody.create(mediaType, bytes)).build();
Request request = new Request.Builder().url("").post(requestBody)
.addHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW")
.addHeader("authorization", "Basic cGFkc2VsZWN0OjQwOWExZmMzZmExNTYwZjljZTYyOTQxZTU2ZDgyOGI2")
.addHeader("cache-control", "no-cache").build();
Response response = null;
try {
response = client.newCall(request).execute();
} catch (Exception e) {
throw new exception(HttpStatus.INTERNAL_SERVER_ERROR,
resource.getString("application.controller.parser.exception"), e);
}
if (!response.isSuccessful() || null == response) {
throw new exception(HttpStatus.INTERNAL_SERVER_ERROR,
resource.getString("application.controller.parser.exception"));
} else {
}
}
return null;
}
任何人都可以告诉我在else部分我需要做什么来转换我作为文件获得的响应并且安全地将其作为我的java代码中的文件。
答案 0 :(得分:0)
将方法返回类型从“File”更改为“byte []”,这将有效。
else {
byte[] responseFile = (File)response.body().bytes();
return responseFile;
}
答案 1 :(得分:0)
使用body()中的byte []构造输入流。使用此输入流写入文件。响应头将让您知道数据类型并相应地定义文件类型