Trying to upload MultipartFile with postman - spring

I am trying to upload a Multipart File using PostMan and getting errors. Here is the code and screenshots:
http://imgur.com/pZ5cXrh
http://imgur.com/NaWQceO
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public void uploadFileHandler(#RequestParam("name") String name,
#RequestParam("name") MultipartFile file) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
// Creating the directory to store file
//String rootPath = System.getProperty("catalina.home");
String rootPath = "C:\\Desktop\\uploads";
File dir = new File(rootPath + File.separator + "tmpFiles");
if (!dir.exists())
dir.mkdirs();
// Create the file on server
File serverFile = new File(dir.getAbsolutePath()
+ File.separator + name);
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
System.out.println("Server File Location="
+ serverFile.getAbsolutePath());
System.out.println("You successfully uploaded file=" + name);
} catch (Exception e) {
System.out.println("You failed to upload " + name + " => " + e.getMessage());
}
} else {
System.out.println("You failed to upload " + name
+ " because the file was empty.");
}
}

You should have a thing like this:
#RequestMapping(value = "/upload", method = RequestMethod.POST, consumes = "multipart/form-data")
public void uploadFileHandler(#RequestParam("name") String name,
#RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
// Creating the directory to store file
//String rootPath = System.getProperty("catalina.home");
String rootPath = "C:\\Users\\mworkman02\\Desktop\\uploads";
File dir = new File(rootPath + File.separator + "tmpFiles");
if (!dir.exists())
dir.mkdirs();
// Create the file on server
File serverFile = new File(dir.getAbsolutePath()
+ File.separator + name);
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
System.out.println("Server File Location="
+ serverFile.getAbsolutePath());
System.out.println("You successfully uploaded file=" + name);
} catch (Exception e) {
System.out.println("You failed to upload " + name + " => " + e.getMessage());
}
} else {
System.out.println("You failed to upload " + name
+ " because the file was empty.");
}
}
Please pay attention to consumes = "multipart/form-data". It is necessary for your uploaded file because you should have a multipart call. You should have #RequestParam("file") MultipartFile file instead of #RequestParam("name") MultipartFile file).
Of course you should have configured a multipartview resolver the built-in support for apache-commons file upload and native servlet 3.

Related

how to write code for viewing s3 bucket image by spring boot api

I write code for download
#GetMapping(value= "/download/{fileName}")
public ResponseEntity<ByteArrayResource> downloadFile(#PathVariable String fileName) {
final byte[] data = amazonClient.downloadFile(fileName);
final ByteArrayResource resource = new ByteArrayResource(data);
return ResponseEntity
.ok()
.contentLength(data.length)
.header("Content-type", "application/octet-stream")
.header("Content-disposition", "attachment; filename=\"" + fileName + "\"")
.body(resource);
}
and the service method for that : -
public byte[] downloadFile(final String fileName) {
byte[] content = null;
logger.info("Downloading an object with key= " + fileName);
final S3Object s3Object = s3client.getObject(bucketName, fileName);
final S3ObjectInputStream stream = s3Object.getObjectContent();
try {
content = IOUtils.toByteArray(stream);
logger.info("File downloaded successfully.");
s3Object.close();
} catch(final IOException ex) {
logger.info("IO Error Message= " + ex.getMessage());
}
return content;
}
but I want to code for the only view not for download.
You can try this way...
AmazonS3 s3Client = new AmazonS3Client(new ProfileCredentialsProvider());
S3Object object = s3Client.getObject(new GetObjectRequest(bucketName, key));
InputStream objectData = object.getObjectContent();
BufferedImage bf = ImageIO.read(objectData);
using javax.imageio

File upload with in Spring MVC without adding any additional parameter in controller method

I am using spring boot 2. My new task is file uploading. I already did it. But I am asked to do it without adding a additional parameter to controller method like #RequestParam("files") MultipartFile files[]. I want to get this from request instead of adding this parameter.
How can I solve this?
I am adding my current code following.
#RequestMapping(value="/uploadMultipleFiles", method=RequestMethod.POST)
public #ResponseBody String handleFileUpload( #RequestParam("files") MultipartFile files[]){
try {
String filePath="c:/temp/kk/";
StringBuffer result=new StringBuffer();
byte[] bytes=null;
result.append("Uploading of File(s) ");
for (int i=0;i<files.length;i++) {
if (!files[i].isEmpty()) {
bytes = files[i].getBytes();
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filePath+files[i].getOriginalFilename())));
stream.write(bytes);
stream.close();
result.append(files[i].getOriginalFilename() + " Ok. ") ;
}
else
result.append( files[i].getOriginalFilename() + " Failed. ");
}
return result.toString();
} catch (Exception e) {
return "Error Occured while uploading files." + " => " + e.getMessage();
}
}
You can get files from HttpRequest:
#RequestMapping(value="/uploadMultipleFiles", method=RequestMethod.POST)
public String handleFileUpload(HttpRequest request){
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> yourFiles = multipartRequest.getFileMap();
return "All is Ok!";
}
My sample code.
#RequestMapping(value = "/multiple/upload", method = RequestMethod.POST)
public #ResponseBody String test(#RequestParam(value = "files[]") List<MultipartFile> files,
HttpServletRequest req) {
MultipartFileWriter writer = new MultipartFileWriter();
String folderPath = "/file/";
for (MultipartFile file : files) {
writer.writeFile(file, folderPath, req);
}
return "success";
}

upload file using rest services in spring mvc

I want to upload a file( any type of file ) into a forlder using web services and spring mvc so I have a sever side and a client side.
On my client side this is the code
#RequestMapping(value = "/uploadMultipleFile", method = RequestMethod.POST , produces="application/json")
public #ResponseBody
Boolean uploadMultipleFileHandler(
#RequestParam("name") MultipartFile[] files) {
MailService ms= new MailService();
Map<String, List<ByteArrayResource>>rval = new HashMap<String, List<ByteArrayResource>>();
String message = "";
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
List<Object> files1 = new ArrayList<>();
List<Object> files2 = new ArrayList<>();
for (int i = 0; i < files.length; i++) {
MultipartFile file = files[i];
System.out.println(file.getOriginalFilename());
try {
byte[] bytes = file.getBytes();
files1.add(new ByteArrayResource(bytes));
files2.add(file.getOriginalFilename());
//System.out.println(map.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
map.put("files", files1);
map.put("names", files2);
System.out.println(map.get("files").toString());
RestTemplate restTemplate = new RestTemplate();
String SERVER_URI="http://localhost:8080/BackEndFinalVersion";
Boolean p=restTemplate.postForObject(SERVER_URI+"/uploadMultipleFile", map, Boolean.class);
System.out.println(p.toString());
//message = message + ms.encodeFileToBase64Binary( bytes);
//rval.put("success",message);
return true;
}
and the server side code is
#RequestMapping(value = "/uploadMultipleFile", method = RequestMethod.POST, produces = "application/json")
public #ResponseBody Boolean uploadMultipleFileHandler(#RequestParam("files") List<Object> files , #RequestParam("names") List<Object> names) {
//MailService ms= new MailService();
//Map<String, Object> rval = new HashMap<String, Object>();
String message = "";
System.out.println("looool");
System.out.println(files);
System.out.println(names);
//System.out.println(files.get(0).toString());
for (int i = 0; i < files.size(); i++) {
System.out.println(files.get(i).getClass());
String file = (String)files.get(i);
try {
byte[] bytes = file.getBytes();
//FileUtils.writeStringToFile(new File("log.txt"), file, Charset.defaultCharset());
// Creating the directory to store file
String rootPath = "C:/Users/Wassim/Desktop/uploads";
File dir = new File(rootPath);
if (!dir.exists())
dir.mkdirs();
File serverFile = new File(dir.getAbsolutePath() + File.separator + ( names.get(i)));
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
//message = message + "You successfully uploaded file=" + ( (MultipartFile) files.get(i)).getOriginalFilename() + "<br />";
//FileUtils.writeByteArrayToFile(new File(dir.getAbsolutePath() + File.separator + files.get(i).getOriginalFilename()), ms.decodeFileToBase64Binary(ms.encodeFileToBase64Binary( bytes)));
//rval.put("success"+i, message);
System.out.println("noooo");
} catch (Exception e) {
message += "You failed to upload " + " => " + e.getMessage();
//rval.put("error", message);
return false;
}
}
return true;
My problem is that this code doesn't work only with .txt files
can any one support me ??

Spring error: IllegalStateException: Cannot call sendRedirect() after the response has been committed and getOutputStream() has already been called

I have got an error when I try to download a zipped file using Spring boot and spring MVC:
Errors:
SEVERE: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed] with root cause
java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed
SEVERE: Servlet.service() for servlet dispatcherServlet threw exception
java.lang.IllegalStateException: getOutputStream() has already been called for this response
Basically, my app is loading a file, zipping it and download the new zip file.
This is my application Controller:
#Controller
public class ApplicationController {
public String fileZipped;
public String inputFile;
#RequestMapping(method = RequestMethod.GET, value = "/uploadForm")
public String provideUploadInfo() {
return "uploadForm";
}
#RequestMapping(method = RequestMethod.POST, value = "/")
public String handleFileUpload(#RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes,
HttpServletResponse downloadResponse) {
if (!file.isEmpty()) {
try {
inputFile = file.getOriginalFilename();
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(new File(Application.UPLOAD_DIR + "/" + inputFile)));
FileCopyUtils.copy(file.getInputStream(), stream);
stream.close();
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded " + file.getOriginalFilename() + "!");
FileUtils.copyDirectory(Application.UPLOAD_DIR, Application.OUTPUT_FOLDER);
FileUtils.cleanDirectory(new File(Application.UPLOAD_DIR));
}
catch (Exception e) {
redirectAttributes.addFlashAttribute("message",
"You failed to upload " + file.getOriginalFilename() + " => " + e.getMessage());
}
}
else {
redirectAttributes.addFlashAttribute("message",
"You failed to upload " + file.getOriginalFilename() + " because the file was empty");
}
return "redirect:/zipFiles";
}
#RequestMapping(value = "/download")
public String handleFileDownload(HttpServletResponse downloadResponse) throws IOException {
InputStream inputStream = null;
OutputStream outStream = null;
try {
if ( fileZipped!=null && Files.exists(Paths.get(fileZipped))) {
inputStream = new FileInputStream(fileZipped);
downloadResponse.setContentType(fileZipped);
downloadResponse.addHeader("Content-Disposition", "attachment; filename=" + Paths.get(fileZipped).getFileName().toString());
outStream = downloadResponse.getOutputStream();
org.apache.commons.io.IOUtils.copy(inputStream, outStream);
downloadResponse.flushBuffer();
}
} catch (IOException e) {
throw new RuntimeException("IOError writing file to output stream");
} finally {
if (inputStream != null) inputStream.close();
if (outStream != null) outStream.close();
}
return "redirect:/uploadForm";
}
#RequestMapping(value="/zipFiles")
public String handleFileZip() throws IOException {
if(inputFile!=null) {
fileZipped = zipFiles(Application.OUTPUT_FOLDER, inputFile);
}
return "redirect:/download";
}
private String zipFiles(String folder, String zipFileName) throws IOException {
String zipFile = folder + "/" + FilenameUtils.removeExtension(zipFileName) + ".zip";
FileOutputStream fileOutputstream = new FileOutputStream(zipFile);
ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(fileOutputstream));
File []filesArray = new File(folder).listFiles();
for (File file : filesArray){
if (!FilenameUtils.getExtension(file.getAbsolutePath()).equals("zip")) {
byte[] buffer = new byte[1024];
FileInputStream fileInputStream = new FileInputStream(file);
zipOutputStream.putNextEntry(new ZipEntry(file.getName()));
int length;
while ((length = fileInputStream.read()) > 0) {
zipOutputStream.write(buffer, 0, length);
}
zipOutputStream.closeEntry();
fileInputStream.close();
}
}
zipOutputStream.close();
return zipFile;
}
I do no know why that is happening if I am closing the input and output streams.
Thanks you very much for your help.
The problem is with the redirect. Instead of
return "redirect:/uploadForm";
return the view name.
return "/uploadForm";

Thymeleaf img not calling spring controler

Here is my gradle dependencies:
dependencies {
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
compile("org.springframework.boot:spring-boot-starter-security")
compile("org.springframework:spring-jdbc:4.1.0.RELEASE")
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("mysql:mysql-connector-java:5.1.+")
compile("org.webjars:bootstrap:3.0.3")
compile("org.webjars:jquery:2.0.3-1")
compile("org.springframework.security.oauth:spring-security-oauth2:2.0.7.RELEASE")
compile("org.springframework.security:spring-security-test:4.0.0.RELEASE")
compile("org.thymeleaf:thymeleaf-spring4")
compile("nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect")
compile("org.springframework.boot:spring-boot-starter-web")
compile("com.google.code.gson:gson:2.2.4")
compile("javax.mail:mail:1.4.5")
compile("org.springframework:spring-context-support:3.2.2.RELEASE")
compile("org.apache.commons:commons-io:1.3.2")
providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")
testCompile("junit:junit")
}
I have defined a method in my controller:
#ResponseBody
#RequestMapping(value = "/mainMenu/companyOfficeMainMenu/imagetest/{server_image_id}", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
public byte[] testphoto(#PathVariable("server_image_id") Long server_image_id) throws IOException {
Image notUpdatedImage = mobileManagment.getImage(server_image_id);
String locationRoot = env.getProperty("location.sever.root");
String locationOfCompanyData = env.getProperty("location.compay.data");
String locationOfImage = env.getProperty("location.compay.media.images");
String storeImageName =
locationOfCompanyData
+ File.separator
+ locationOfImage
+ File.separator
+ notUpdatedImage.getCompany_id()
+ File.separator +
+ notUpdatedImage.getServer_questionnaire_attempt_key()
+ File.separator
+ notUpdatedImage.getImage_name();
File uploadedFile = new File(locationRoot, storeImageName);
InputStream inputStream = new FileInputStream(uploadedFile.getAbsolutePath());
return IOUtils.toByteArray(inputStream);
}
And in Thymeleaf, I try to call it:
<img th:src="#{/mainMenu/companyOfficeMainMenu/imagetest/${object.getServer_image_id()}}" />
I have a break point in the method in the controller but it's not being called.
Here is also another method that does not get called:
#RequestMapping(value = "/mainMenu/companyOfficeMainMenu/image/{server_image_id}", method = RequestMethod.GET)
public ResponseEntity<byte[]> getImage(#PathVariable("server_image_id") Long server_image_id) throws IOException {
Image notUpdatedImage = mobileManagment.getImage(server_image_id);
String locationRoot = env.getProperty("location.sever.root");
String locationOfCompanyData = env.getProperty("location.compay.data");
String locationOfImage = env.getProperty("location.compay.media.images");
String storeImageName =
locationOfCompanyData
+ File.separator
+ locationOfImage
+ File.separator
+ notUpdatedImage.getCompany_id()
+ File.separator +
+ notUpdatedImage.getServer_questionnaire_attempt_key()
+ File.separator
+ notUpdatedImage.getImage_name();
File uploadedFile = new File(locationRoot, storeImageName);
InputStream inputStream = new FileInputStream(uploadedFile.getAbsolutePath());
byte[] imageContent = IOUtils.toByteArray(inputStream);
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_PNG);
return new ResponseEntity<byte[]>(imageContent, headers, HttpStatus.OK);
}
#ResponseBody
#RequestMapping(value = "/mainMenu/companyOfficeMainMenu/imagetest/{server_image_id}", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
public byte[] testphoto(#PathVariable("server_image_id") Long server_image_id) throws IOException {
Image notUpdatedImage = mobileManagment.getImage(server_image_id);
String locationRoot = env.getProperty("location.sever.root");
String locationOfCompanyData = env.getProperty("location.compay.data");
String locationOfImage = env.getProperty("location.compay.media.images");
String storeImageName =
locationOfCompanyData
+ File.separator
+ locationOfImage
+ File.separator
+ notUpdatedImage.getCompany_id()
+ File.separator +
+ notUpdatedImage.getServer_questionnaire_attempt_key()
+ File.separator
+ notUpdatedImage.getImage_name();
File uploadedFile = new File(locationRoot, storeImageName);
InputStream inputStream = new FileInputStream(uploadedFile.getAbsolutePath());
return IOUtils.toByteArray(inputStream);
}
When I press f12 on the screen I can see the output of the image tag:
<img src="/mainMenu/companyOfficeMainMenu/image/${object.getServer_image_id()}">
That does not look right.
When I output I get 27 (which is correct)
<p th:text="${object.getServer_image_id()}"></p>
You're not using the Thymeleaf Link URL syntax correctly. You need to specify a parameter in braces (similar to the #RequestMapping) eg. {server_image_id}. Then you specify the value to replace it with afterwards between parenthesis (server_image_id=${object.getServer_image_id()}).
All together:
<img th:src="#{/mainMenu/companyOfficeMainMenu/imagetest/{server_image_id}(server_image_id=${object.getServer_image_id()})}" />

Resources