PareekSandeep
PareekSandeep

Reputation: 430

multipart form POST submit request fetching broken files

I am having trouble uploading files correctly.

Summary of my problem: Any files being uploaded (*.docx, *.pdf, *.jpg/png/bmp etc.) are received as broken on server side.

My Environment: JSP + Spring 3 MVC + Java.

I have tried different approaches including one suggested by here by BalusC, but failed. Original picture distorted after upload

These are example uploads which have failed badly.

My Code: tempform.jsp

<form:form method="POST" acceptCharset="ISO-8859-15" action="submit.htm"
commandName="commandform" enctype="multipart/form-data" >
...
<input  name ="file0[] type="file" id="file0" multiple>
...
<input type="submit" name="submit">

controller.java

@RequestMapping(value = "/submit", method = RequestMethod.POST)
public ModelAndView submitRequest(@ModelAttribute("commandform") Request req, HttpServletRequest request, HttpServletResponse response, ModelMap model){
try {
 MultipartHttpServletRequest tempPart = (MultipartHttpServletRequest) httpReq;
         //file being transported is original.jpg and is only one.
         MultipartFile filePart = tempPart.getFile("file0[]");
         String fileName1 = filePart.getOriginalFilename();
         InputStream fileContent = filePart.getInputStream();

         //printing file here in this step for debugging purpose. Using jpg type only for example purpose.
         BufferedImage bImageFromConvert = ImageIO.read(fileContent);
         ImageIO.write(bImageFromConvert, "jpg", new File(
                "e:/mynewfile.jpg"));
         //file is created at location but with distorted version as shown in image.
         ...
}catch(Exception ex){
...
}
}

My doubt: Is content type responsible for this behavior? I am forcing CharacterEncodingFilter with <init-param> value as ISO-8859-15 in my web.xml. I have used ISO-8859-15 encoding in jsp page as well because I have to deal with European text as well. Any help or guidance will be most welcome. Thanks in advance.

Upvotes: 4

Views: 1703

Answers (1)

Darren Parker
Darren Parker

Reputation: 1812

I don't think the problem is with the acceptCharset="ISO-8859-15"
I put together a test case (using Spring boot ) based on a Getting Started guide from Spring IO website: Spring IO file upload example

I have also coded a Spring 3 MVC controller for a project at work that does file uploads. It is similar to the example that I show below.

Using this Spring boot test case, I can upload your example image with both UTF-8 and ISO-8859-15. It works fine. Granted, I'm not using the CharacterEncodingFilter like you are.
Here is some of my code, so you can compare to yours.

I hope it helps.

Application.java:

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application extends SpringBootServletInitializer {

    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setMaxFileSize("128KB");
        factory.setMaxRequestSize("128KB");
        return factory.createMultipartConfig();
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

FileUploadController.java:

@Controller
public class FileUploadController {

    @RequestMapping("/")
    public String welcome() {
        return "welcome";
    }

    @RequestMapping(value="/upload", method=RequestMethod.GET)
    public @ResponseBody String provideUploadInfo() {
        return "You can upload a file by posting to this same URL.";
    }

    @RequestMapping(value="/upload", method=RequestMethod.POST)
    public @ResponseBody String handleFileUpload(@RequestParam("name") String name, 
            @RequestParam("file") MultipartFile file){
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream = 
                        new BufferedOutputStream(new FileOutputStream(new File(name)));
                stream.write(bytes);
                stream.close();
                return "You successfully uploaded " + name + " into " + name;
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + name + " because the file was empty.";
        }
    }
}

snippet of welcome.jsp:

<%-- 
<form:form action="upload" method="POST" acceptCharset="UTF-8" enctype="multipart/form-data"  >
--%>
<form:form action="upload" method="POST" acceptCharset="ISO-8859-15" enctype="multipart/form-data"  >
  <table>
      <tr>
        <td>  
            <!-- <input type="hidden" name="action" value="upload" />  -->
            <strong>Please select a file to upload :</strong> <input type="file" name="file" />
        </td>
      </tr>
      <tr>
        <td>Name: <input type="text" name="name"><br />
        </td>
      </tr>
      <tr>
        <td>
         <input type="submit" value="Upload"> Press here to upload the file!
        </td>
      </tr>
  </table>
</form:form>

Upvotes: 2

Related Questions