How do I upload a file to a Spring MVC controller

时间:2016-08-31 16:56:10

标签: spring spring-mvc file-upload

I am trying to pass the resume back to the Spring MVC controller. I have created a user class that saves resume/files

public class User {

private int id;
private String firstName;
private String lastName;
private String city;
private String state;
private String zip;
private String username;
private String password;
private int enabled;
private byte[] resume;

//getters/setters for them all

and the controller to take in the uploaded form from the site

@Controller
@RequestMapping(value = "/user")
public class UserController {

UserDao uDao;

@Inject
public UserController(UserDao uDao) {
    this.uDao = uDao;
}

@RequestMapping(value = "/profile", method = RequestMethod.GET)
public String postPage(Principal principal, Map model) {

    String name = principal.getName();
    User u = uDao.getByUsername(name);

    String fName = u.getFirstName();
    String lName = u.getLastName();
    String city = u.getCity();
    String state = u.getState();
    String zip = u.getZip();
    String bc = u.getBootcampAttended();

    model.put("fName", fName);
    model.put("lName", lName);
    model.put("city", city);
    model.put("state", state);
    model.put("zip", zip);
    model.put("bc", bc);

    return "user";
}

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String Upload(@RequestParam("file") MultipartFile file, Principal principal) throws IOException {
    if (!file.isEmpty()) {
        byte[] bytes = file.getBytes(); // alternatively, file.getInputStream();
        // application logic

        String name = principal.getName();
        User u = uDao.getByUsername(name);
        u.setResume(bytes);
        uDao.update(u);

        return "user";
    }
    return "user";

}

}

I am trying to pass the resume to display as a clickable file on the jsp in the postPage method. Here is the jsp

            <h1>${fName}</h1>
            <h1>${lName}</h1>
            <h1>${state}</h1>
            <h1>${city}</h1>
            <h1>${zip}</h1>
            <h1>${bc}</h1>

            <form method="POST" action="${pageContext.request.contextPath}/user/upload" enctype="multipart/form-data">
                <table border="0">
                    <tr>
                        <td>Pick file #1:</td>
                        <td><input type="file" name="file" size="50" /></td>
                        <td><input type="submit" value="Upload"/>
                    </tr>
                </table>
            </form>

Any tips on how to get the file on the Spring MVC controller. Preferably to be the value of the file input as default, instead of it saying "No File Chosen". Was thinking that maybe I could convert the file back into the MultiPartFile, like how I uploaded it, but im not sure how to pass that back to the Spring MVC controller.

Thanks!

0 个答案:

没有答案
相关问题